Esempio n. 1
0
        //private List<StrategyBase> _strategies;

        /// <summary>
        /// Initializes a new instance of the <see cref="ClassCodeGenerator"/> class.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="port">The port.</param>
        public ClassCodeGenerator(ProjectItem item, ClassImplementation port)
        {
            //_strategies = new List<StrategyBase>();
            //foreach( StrategyBase strategy in port.GetStrategies(true) )
            //{
            //    IStrategyInjectCode si = strategy as IStrategyInjectCode;
            //    if( si == null || ( strategy is IStrategyInterface ) )
            //        continue;

            //    _strategies.Add( strategy );
            //}
        }
        public void Execute( )
        {
            if (Context.GenerationPass == GenerationPass.ElementAdded)
            {
                return;
            }

            try
            {
                ClassImplementation clazz = CurrentElement as ClassImplementation;
                if (clazz == null)
                {
                    return;
                }

                Project prj      = Context.Project;
                string  fileName = null;

                // Création du code à personnaliser
                if (!String.IsNullOrEmpty(CustomCodeTemplate) && !String.IsNullOrEmpty(CustomCodeFilePattern))
                {
                    fileName = String.Format(CustomCodeFilePattern, clazz.Name);
                    fileName = CallT4Template(Context.Project,
                                              CustomCodeTemplate,
                                              clazz,
                                              fileName);

                    if (!String.IsNullOrEmpty(fileName))
                    {
                        // Par défaut, ce fichier n'est pas regénérable
                        Mapper.Instance.SetCanGeneratePropertyValue(fileName, false);
                    }
                }

                // Création de la classe d'implémentation
                if (ClassGenerateDoubleDerivate.GetValue(clazz) && !String.IsNullOrEmpty(Template))
                {
                    fileName = CallT4Template(Context.Project,
                                              Template,
                                              clazz,
                                              clazz.Name + "Base");
                }
            }
            catch (Exception ex)
            {
                LogError(ex);
            }
        }
        /// <summary>
        /// Constructeur prenant le shape courant
        /// </summary>
        /// <param name="obj">The obj.</param>
        public PropagatesOperationsCommand(object obj)
        {
            LinkShape shape = obj as LinkShape;

            if (shape != null && shape.ModelElement is ClassUsesOperations)
            {
                ClassImplementation clazz = ((ClassUsesOperations)shape.ModelElement).Source as ClassImplementation;
                if (clazz == null)
                {
                    return;
                }

                _sources.Add(clazz);
                if (clazz.Contract != null)
                {
                    _sources.Add(clazz.Contract);
                }

                TypeWithOperations target = (TypeWithOperations)((ClassUsesOperations)shape.ModelElement).TargetService;
                if (target == null)
                {
                    Debug.Assert(((ClassUsesOperations)shape.ModelElement).ExternalTargetService != null);
                    _targets.Add(((ClassUsesOperations)shape.ModelElement).ExternalTargetService.ReferencedServiceContract);
                }
                else
                {
                    _targets.Add(target);
                }
            }

            if (shape != null && shape.ModelElement is Implementation)
            {
                _sources.Add(((Implementation)shape.ModelElement).Contract);
                ClassImplementation clazz = ((Implementation)shape.ModelElement).ClassImplementation;
                _targets.Add(clazz);
                if (clazz.Contract != null)
                {
                    _targets.Add(clazz.Contract);
                }
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Creates the DAO.
        /// </summary>
        public void CreateDAO()
        {
            if (rbNone.Checked)
            {
                return;
            }

            if (rbSelect.Checked)
            {
                ClassImplementation port = cbDAO.SelectedItem as ClassImplementation;
                port.AssociatedEntity = _entity;
            }
            else if (rbNew.Checked)
            {
                ClassImplementation port = new ClassImplementation(_dataAccessLayer.Store);
                port.Name             = txtDAOName.Text;
                port.RootName         = _entity.RootName;
                port.AssociatedEntity = _entity;
                _dataAccessLayer.Classes.Add(port);

                UnplacedModelHelper.RegisterNewModel(_dataAccessLayer.Store, port);
            }
        }
Esempio n. 5
0
        // Création du fichier de mapping nhibernate en utilisant le mécanisme de
        // mappage filtrée
        public void Execute()
        {
            try
            {
                DataLayer ml = CurrentElement as DataLayer;
                if (ml != null && Context.GenerationPass == GenerationPass.MetaModelUpdate && GenerateConfigurationSettings)
                {
                    GenerateNHibernateConfiguration(ml);

                    return;
                }

                PresentationLayer layer = CurrentElement as PresentationLayer;
                if (layer != null && Context.GenerationPass == GenerationPass.MetaModelUpdate)
                {
                    if (layer.HostingContext == HostingContext.Web && GeneratePredefinedSessionManager)
                    {
                        layer.AddXmlConfigurationContent("nhibernatehttpModule", @"<configuration>
<system.web><httpModules><add name=""NHibernateSessionModule"" type=""NHibernate.Web.NHibernateSessionModule""/></httpModules></system.web>
</configuration>");
                    }
                    else
                    {
                        layer.AddXmlConfigurationContent("nhibernatehttpModule", null);
                    }
                    return;
                }

                // DAO
                if (CurrentElement is DataAccessLayer && GeneratePredefinedSessionManager)
                {
                    DataAccessLayer dal = CurrentElement as DataAccessLayer;
                    CallT4Template(Context.Project, "NHibernateSessionManager", dal, "NHibernateSessionManager.cs");
                    PresentationLayer l = dal.Component.GetMainLayer() as PresentationLayer;
                    if (l != null && l.HostingContext == HostingContext.Web)
                    {
                        CallT4Template(Context.Project, "NHibernateHttpModule", dal, "NHibernateHttpModule.cs");
                    }
                    return;
                }

                ClassImplementation clazz = CurrentElement as ClassImplementation;
                if (clazz != null && !String.IsNullOrEmpty(DAOTemplate))
                {
                    DataAccessLayer dal = clazz.Layer as DataAccessLayer;
                    if (dal != null && dal.SoftwareComponent.IsDataLayerExists)
                    {
                        TemplateProperties properties = new TemplateProperties();
                        CallT4Template(Context.Project, DAOTemplate, clazz, clazz.Name + "Base");
                    }
                    return;
                }

                Entity entity = CurrentElement as Entity;
                if (entity != null && EntityIsPersistableProperty.GetValue(entity) && !String.IsNullOrEmpty(EntityTemplate))
                {
                    CallT4Template(Context.Project, EntityTemplate, entity, entity.Name);
                }

                Enumeration enumeration = CurrentElement as Enumeration;
                if (enumeration != null && !String.IsNullOrEmpty(EnumTemplate))
                {
                    CallT4Template(Context.Project, EnumTemplate, enumeration, enumeration.Name);
                }

                // Mappings
                if (CurrentElement is DataLayer && Context.GenerationPass == GenerationPass.CodeGeneration && GenerateHbmFile)
                {
                    // Nom du fichier de sortie
                    string fileName           = String.Format("{0}.hbm.xml", System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Context.Project.FileName), Context.Project.Name));
                    NHibernate3Strategy strat = new NHibernate3Strategy();
                    if (File.Exists(fileName))
                    {
                        ServiceLocator.Instance.ShellHelper.EnsureCheckout(fileName);
                    }

                    strat.Execute(Context, fileName);

                    if (File.Exists(fileName))
                    {
                        ProjectItem item = ServiceLocator.Instance.ShellHelper.AddFileToProject(Context.Project, fileName);

                        try
                        {
                            item.Properties.Item("BuildAction").Value = _hbmFileBuildAction;
                        }
                        catch { }

                        if (_hbmFileBuildAction != VSLangProj.prjBuildAction.prjBuildActionEmbeddedResource)
                        {
                            ((DataLayer)CurrentElement).AddReference(fileName, ArtifactType.Content);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogError(ex);
            }
        }
Esempio n. 6
0
        private void addBehaviorClassToXmlElement(XElement behavior, List <XNamespace> namespaces, out List <XAttribute> additionalTagPrefixes)
        {
            additionalTagPrefixes = null;
            if (behavior == null)
            {
                return;
            }

            if (ClassImplementation != null)
            {
                XElement behaviorElement = new XElement(CLASS);
                behavior.Add(behaviorElement);

                Type behaviorType = ClassImplementation.GetType();
                XmlnsDefinitionAttribute defnAttribute = null;
                object[] attribs = behaviorType.Assembly.GetCustomAttributes(typeof(XmlnsDefinitionAttribute), false);
                if (attribs != null && attribs.Length > 0)
                {
                    defnAttribute = attribs[0] as XmlnsDefinitionAttribute;
                }

                string behaviorNamespace = behaviorType.Namespace;
                string namespaceMapping  = null;
                if (defnAttribute != null)
                {
                    namespaceMapping = defnAttribute.XmlNamespace;
                }
                else
                {
                    namespaceMapping = string.Format("clr-namespace:{0};assembly={1}", behaviorNamespace, behaviorType.Assembly.FullName.Split(',')[0]);
                }

                XNamespace namespaceForCommand = namespaces.FirstOrDefault <XNamespace>(x => x.NamespaceName == namespaceMapping);
                if (namespaceForCommand == null)
                {
                    namespaceForCommand = namespaceMapping;
                    string tagPrefix = behaviorNamespace.Replace('.', '_');

                    if (additionalTagPrefixes == null)
                    {
                        additionalTagPrefixes = new List <XAttribute>();
                    }

                    additionalTagPrefixes.Add(new XAttribute(XNamespace.Xmlns + tagPrefix, namespaceMapping));
                }

                XElement behaviorCommandImplElement = new XElement(namespaceForCommand + behaviorType.Name);
                behaviorElement.Add(behaviorCommandImplElement);

                ISupportsConfiguration supportsConfiguration = ClassImplementation as ISupportsConfiguration;
                if (supportsConfiguration != null)
                {
                    //string configData = null;
                    //try
                    //{
                    //    configData = supportsConfiguration.SaveConfiguration();
                    //}
                    //catch (Exception ex)
                    //{
                    //    Logger.Instance.LogError(ex);
                    //    OnBehaviorClassSaveConfigurationException(new ExceptionEventArgs(ex, null));
                    //}
                    if (!string.IsNullOrWhiteSpace(ConfigData))
                    {
                        ConfigData = ConfigData.Trim();
                        XElement configDataElement = new XElement(CONFIG_DATA);
                        if (ConfigData.StartsWith("<", StringComparison.Ordinal) && ConfigData.EndsWith(">", StringComparison.Ordinal))
                        {
                            try
                            {
                                XDocument xDoc = XDocument.Parse(ConfigData);
                                configDataElement.Add(xDoc.Root);
                            }
                            catch
                            {
                                configDataElement.Value = ConfigData;
                            }
                        }
                        else
                        {
                            configDataElement.Value = ConfigData;
                        }
                        behavior.Add(configDataElement);
                    }
                }
            }
        }
        /// <summary>
        /// Alerts listeners that a property for an element has changed.
        /// </summary>
        /// <param name="e">Provides data for the ElementPropertyChanged event.</param>
        public override void ElementPropertyChanged(ElementPropertyChangedEventArgs e)
        {
            // Teste si on est en train de charger le modèle
            // Permet d'eviter de déclencher une régle lors du chargement du modèle
            if (e.ModelElement.Store.TransactionManager.CurrentTransaction.TopLevelTransaction.IsSerializing ||
                e.ModelElement.Store.InUndoRedoOrRollback)
            {
                return;
            }
            object value;

            // On ignore
            if (
                e.ModelElement.Store.TransactionManager.CurrentTransaction.TopLevelTransaction.Context.ContextInfo.
                TryGetValue("CustomizableElementChangeRule_Enabled", out value) &&
                (bool)value == false)
            {
                return;
            }

            CandleElement elem = e.ModelElement as CandleElement;

            if (elem == null)
            {
                return;
            }

            // Teste l'élément
            //if (e.DomainProperty.Id == ClassImplementation.NameDomainPropertyId)
            //{
            //    if (String.IsNullOrEmpty(elem.RootName) || elem.RootName == (string)e.OldValue)
            //        elem.RootName = elem.Name;
            //}

            if (e.DomainProperty.Id == CandleElement.RootNameDomainPropertyId)
            {
                string oldValue           = (string)e.OldValue;
                ClassImplementation model = e.ModelElement as ClassImplementation;
                if (model != null)
                {
                    // NON si on force le root name, c'est qu'on veut changer le nom
                    //string oldName = String.IsNullOrEmpty(oldValue) ? null : StrategyManager.GetInstance(model.Store).NamingStrategy.CreateElementName(model.Layer, oldValue);
                    //if( String.IsNullOrEmpty(elem.Name) || elem.Name == oldName || String.IsNullOrEmpty(oldValue))
                    elem.Name =
                        StrategyManager.GetInstance(model.Store).NamingStrategy.CreateElementName(model.Layer,
                                                                                                  (string)e.NewValue);

                    if (model.Contract != null)
                    {
                        model.Contract.RootName = model.RootName;
                    }
                }

                ServiceContract contract = e.ModelElement as ServiceContract;
                if (contract != null && contract.Layer != null && contract.Name == "?")
                // Layer est null si on a à faire à un ExternalServiceContract
                {
                    //string oldName = StrategyManager.GetInstance(clazz.Store).NamingStrategy.CreateElementName(contract.Layer, (string)e.OldValue);
                    //if (String.IsNullOrEmpty(elem.Name) || elem.Name == oldName)
                    elem.Name =
                        StrategyManager.GetInstance(contract.Store).NamingStrategy.CreateElementName(contract.Layer,
                                                                                                     (string)e.NewValue);
                }

                Entity entity = e.ModelElement as Entity;
                if (entity != null)
                {
                    DataLayer modelsLayer = entity.Package.Layer;
                    string    oldName     = String.IsNullOrEmpty(oldValue)
                                         ? null
                                         : StrategyManager.GetInstance(model.Store).NamingStrategy.CreateElementName(
                        model.Layer, oldValue);
                    if (String.IsNullOrEmpty(elem.Name) || elem.Name == oldName || String.IsNullOrEmpty(oldValue))
                    {
                        elem.Name =
                            StrategyManager.GetInstance(elem.Store).NamingStrategy.CreateElementName(modelsLayer,
                                                                                                     (string)e.NewValue);
                    }
                }
            }
        }
Esempio n. 8
0
        void IStrategyCodeInjector.OnMetaModelUpdate(CodeInjectionContext context)
        {
            // Reference pour le ServiceLocator
            if (context.CurrentElement is Layer)
            {
                Layer layer = context.CurrentElement as Layer;
                foreach (ClassImplementation clazz in layer.Classes)
                {
                    foreach (ClassUsesOperations service in ClassUsesOperations.GetLinksToServicesUsed(clazz))
                    {
                        if (!context.GenerationContext.Mode.CheckConfigurationMode(service.ConfigurationMode) || service.TargetService is ExternalServiceContract)
                        {
                            continue;
                        }

                        foreach (Implementation impl in Implementation.GetLinksToImplementations((ServiceContract)service.TargetService))
                        {
                            if (context.GenerationContext.Mode.CheckConfigurationMode(impl.ConfigurationMode))
                            {
                                if (CheckAllHandler(impl.ClassImplementation, impl.ClassImplementation.Layer))
                                {
                                    layer.AddReferenceToService(entLibId, "EnterpriseLibrary", new VersionInfo(3, 1, 0, 0), "Microsoft.Practices.EnterpriseLibrary.PolicyInjection");
                                    return;
                                }
                            }
                        }
                    }
                }
            }

            if (context.CurrentElement is ClassImplementation)
            {
                ClassImplementation clazz = context.CurrentElement as ClassImplementation;
                if (clazz.Contract == null)
                {
                    return;
                }

                bool flag = false;
                foreach (Operation op in clazz.Contract.Operations)
                {
                    IPIABHandler handler = CheckHandler <LogCallHandler>(LogCallHandlerProperty, op, clazz);
                    if (handler != null && handler.Enabled)
                    {
                        ((ClassImplementation)context.CurrentElement).Layer.AddReferenceToService(entLibId, "EnterpriseLibrary", new VersionInfo(3, 1, 0, 0), "Microsoft.Practices.EnterpriseLibrary.Logging", ReferenceScope.Runtime, "*");
                        flag = true;
                    }

                    handler = CheckHandler <CacheCallHandler>(CacheCallHandlerProperty, op, clazz);
                    if (handler != null && handler.Enabled)
                    {
                        ((ClassImplementation)context.CurrentElement).Layer.AddReferenceToService(entLibId, "EnterpriseLibrary", new VersionInfo(3, 1, 0, 0), "Microsoft.Practices.EnterpriseLibrary.Caching", ReferenceScope.Runtime, "*");
                        flag = true;
                    }

                    // PerformanceCounterCallHandler
                    handler = CheckHandler <PerformanceCounterCallHandler>(PerformanceCounterCallHandlerProperty, op, clazz);
                    if (handler != null && handler.Enabled)
                    {
                        ((ClassImplementation)context.CurrentElement).Layer.AddReferenceToService(entLibId, "EnterpriseLibrary", new VersionInfo(3, 1, 0, 0), "Microsoft.Practices.EnterpriseLibrary.Common.Instrumentation", ReferenceScope.Runtime, "*");
                        flag = true;
                    }
                }

                if (flag)
                {
                    ((ClassImplementation)context.CurrentElement).Layer.AddReferenceToService(entLibId, "EnterpriseLibrary", new VersionInfo(3, 1, 0, 0), "Microsoft.Practices.EnterpriseLibrary.PolicyInjection");
                    ((ClassImplementation)context.CurrentElement).Layer.AddReferenceToService(entLibId, "EnterpriseLibrary", new VersionInfo(3, 1, 0, 0), "Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers", ReferenceScope.Runtime | ReferenceScope.Compilation, "*");
                }
            }
        }
Esempio n. 9
0
        void IStrategyCodeInjector.OnGenerateFunction(CodeInjectionContext context, DSLFactory.Candle.SystemModel.CodeGeneration.CodeModel.CandleCodeFunction function)
        {
            // Service factory
            if (context.CurrentElement is Layer)
            {
                // On part du principe que le template du servicelocator à généré une classe nommée ServiceLocator et
                // une méthode par création d'instance dont le nom commence par CreateInstanceOfxxxxxx
                if (function.Parent.Name == "ServiceLocatorBase" && function.Name.StartsWith("CreateInstanceOf"))
                {
                    string currentName = function.Name.Substring("CreateInstanceOf".Length);
                    foreach (ClassImplementation clazz in ((Layer)context.CurrentElement).Classes)
                    {
                        foreach (ClassUsesOperations service in ClassUsesOperations.GetLinksToServicesUsed(clazz))
                        {
                            if (!context.GenerationContext.Mode.CheckConfigurationMode(service.ConfigurationMode) || service.TargetService is ExternalServiceContract)
                            {
                                continue;
                            }

                            ServiceContract contract = service.TargetService as ServiceContract;
                            if (contract == null)
                            {
                                continue;
                            }

                            foreach (Implementation impl in Implementation.GetLinksToImplementations(contract))
                            {
                                if (context.GenerationContext.Mode.CheckConfigurationMode(impl.ConfigurationMode) && impl.ClassImplementation.Name == currentName)
                                {
                                    if (impl.ClassImplementation.Contract != null)
                                    {
                                        foreach (Operation op in impl.ClassImplementation.Contract.Operations)
                                        {
                                            if (CheckAllHandler(op, impl.ClassImplementation))
                                            {
                                                function.ReplaceBody(
                                                    @"           string path = ConfigurationManager.AppSettings[key];
            Type t = Assembly.Load(path).GetType(""" + impl.ClassImplementation.FullName + @""");
            PropertyInfo p = typeof(Microsoft.Practices.EnterpriseLibrary.PolicyInjection.PolicyInjection).GetProperty(""DefaultPolicyInjector"", BindingFlags.Static | BindingFlags.NonPublic);
            Microsoft.Practices.EnterpriseLibrary.PolicyInjection.PolicyInjector pi = (Microsoft.Practices.EnterpriseLibrary.PolicyInjection.PolicyInjector)p.GetValue(null, null);
            return (" + contract.FullName + ")pi.Create(t, typeof(" + contract.FullName + @"));
");
                                                return;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // Attribut
            if (context.CurrentElement is ClassImplementation)
            {
                ClassImplementation clazz = context.CurrentElement as ClassImplementation;
                if (clazz.Name + "Base" == function.Parent.Name || clazz.Name == function.Parent.Name)
                {
                    Operation op = function.FindOperationFromContract(clazz.Contract);
                    if (op != null)
                    {
                        // LogCallHandler
                        IPIABHandler handler = CheckHandler <LogCallHandler>(LogCallHandlerProperty, op, clazz);
                        if (handler != null && handler.Enabled)
                        {
                            handler.SetAttribute(context, function);
                        }


                        // CacheCallHandler
                        handler = CheckHandler <CacheCallHandler>(CacheCallHandlerProperty, op, clazz);
                        if (handler != null && handler.Enabled)
                        {
                            handler.SetAttribute(context, function);
                        }

                        // PerformanceCounterCallHandler
                        handler = CheckHandler <PerformanceCounterCallHandler>(PerformanceCounterCallHandlerProperty, op, clazz);
                        if (handler != null && handler.Enabled)
                        {
                            handler.SetAttribute(context, function);
                        }
                    }
                }
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Imports the operations.
        /// </summary>
        /// <param name="layer">The layer.</param>
        /// <param name="port">The port.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <returns>true if the import is ok</returns>
        public bool ImportOperations(SoftwareLayer layer, TypeWithOperations port, string fileName)
        {
            FileCodeModel fcm = ServiceLocator.Instance.ShellHelper.GetFileCodeModel(fileName);

            if (fcm == null)
            {
                return(false);
            }

            foreach (CodeElement cn in fcm.CodeElements)
            {
                if (cn is CodeNamespace)
                {
                    foreach (CodeElement ci in ((CodeNamespace)cn).Members)
                    {
                        if ((ci is CodeInterface || ci is CodeClass) && layer is InterfaceLayer)
                        {
                            CodeElements members;
                            string       comment;
                            if (ci is CodeInterface)
                            {
                                comment = ((CodeInterface)ci).DocComment;
                                members = ((CodeInterface)ci).Members;
                            }
                            else
                            {
                                comment = ((CodeClass)ci).DocComment;
                                members = ((CodeClass)ci).Members;
                            }
                            if (port == null)
                            {
                                port          = new ServiceContract(layer.Store);
                                port.Name     = ci.Name;
                                port.RootName = ci.Name;
                                port.Comment  = NormalizeComment(comment);
                                ((InterfaceLayer)layer).ServiceContracts.Add((ServiceContract)port);
                            }

                            RetrieveOperations(port, members, false);
                        }
                        else if (ci is CodeClass && layer is Layer)
                        {
                            CodeClass           cc    = ci as CodeClass;
                            ClassImplementation clazz = port as ClassImplementation;
                            //if (cc.Access == vsCMAccess.vsCMAccessPublic)
                            {
                                if (clazz == null)
                                {
                                    clazz          = new ClassImplementation(layer.Store);
                                    clazz.Name     = ci.Name;
                                    clazz.RootName = ci.Name;
                                    clazz.Comment  = NormalizeComment(cc.DocComment);
                                    ((Layer)layer).Classes.Add(clazz);
                                }

                                InterfaceLayer iLayer = clazz.Layer.LayerPackage.InterfaceLayer;
                                // Si il y a plusieurs interfaces, on ne fait rien car on ne sait pas laquelle prendre
                                if (iLayer != null && cc.ImplementedInterfaces.Count == 1)
                                {
                                    ServiceContract contract = clazz.Contract;
                                    if (contract == null)
                                    {
                                        string iName = cc.ImplementedInterfaces.Item(1).Name;
                                        contract = iLayer.ServiceContracts.Find(delegate(ServiceContract c) { return(c.Name == iName); });
                                        if (contract == null)
                                        {
                                            contract          = new ServiceContract(layer.Store);
                                            contract.Name     = StrategyManager.GetInstance(clazz.Store).NamingStrategy.CreateElementName(iLayer, cc.Name);
                                            contract.RootName = cc.Name;
                                            contract.Comment  = NormalizeComment(cc.DocComment);
                                            iLayer.ServiceContracts.Add(contract);
                                            RetrieveOperations(contract, cc.Members, true);
                                        }
                                        clazz.Contract = contract;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(true);
        }
Esempio n. 11
0
        /// <summary>
        /// Execution du wizard
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="DSLFactory.Candle.SystemModel.Strategies.StrategyElementElementAddedEventArgs"/> instance containing the event data.</param>
        public void RunWizard(ModelElement sender, StrategyElementElementAddedEventArgs e)
        {
            CandleElement elem = e.ModelElement as CandleElement;

            txtRootName.Text = elem.RootName;

            if (elem is ServiceContract) // Ce cas est désactivé (voir selection du wizard)
            {
                _layer       = ((ServiceContract)e.ModelElement).Layer;
                txtName.Text =
                    StrategyManager.GetInstance(_layer.Store).NamingStrategy.CreateElementName(_layer, elem.RootName);
            }
            else
            {
                _layer       = ((ClassImplementation)e.ModelElement).Layer;
                _iLayer      = ((ClassImplementation)e.ModelElement).Layer.LayerPackage.InterfaceLayer;
                txtName.Text =
                    StrategyManager.GetInstance(_layer.Store).NamingStrategy.CreateElementName(_layer, elem.RootName);
                if (_iLayer == null)
                {
                    txtContractName.Visible = false;
                }
                else
                {
                    txtContractName.Text =
                        StrategyManager.GetInstance(_layer.Store).NamingStrategy.CreateElementName(_iLayer, txtName.Text);
                }
            }

            if (elem is ServiceContract || ((ClassImplementation)elem).Layer.LayerPackage.InterfaceLayer == null)
            {
                lblContractName.Visible = false;
                txtContractName.Visible = false;
                txtContractName.Text    = null;
            }

            lblHeader.Text = String.Format(lblHeader.Text, _layer.Name);
            groupBox1.Text = _layer.Namespace;

            if (!s_dontShow)
            {
                e.UserCancel = (ShowDialog() == DialogResult.Cancel);
                if (e.UserCancel)
                {
                    return;
                }
                s_dontShow = ckDontShow.Checked;
            }

            // Ici on force les noms des classes donc on ne veut pas que la régle basée sur la modification
            // du RootName s'execute. On l'indique dans le contexte de la transaction
            if (
                !elem.Store.TransactionManager.CurrentTransaction.TopLevelTransaction.Context.ContextInfo.ContainsKey(
                    "CustomizableElementChangeRule_Enabled"))
            {
                elem.Store.TransactionManager.CurrentTransaction.TopLevelTransaction.Context.ContextInfo.Add(
                    "CustomizableElementChangeRule_Enabled", false);
            }
            elem.Name = txtName.Text;

            using (Transaction transaction = elem.Store.TransactionManager.BeginTransaction("Set root name"))
            {
                // Force la transaction pour que la règle s'execute tout de suite et qu'on puisse
                // forcer le nom ensuite
                elem.RootName = txtRootName.Text;
                transaction.Commit();
            }

            // Si c'est une classe, on essaye de créer son interface
            ClassImplementation clazz = elem as ClassImplementation;

            if (clazz != null && _iLayer != null && !String.IsNullOrEmpty(txtContractName.Text))
            {
                if (clazz.Contract == null)
                {
                    // On regarde si l'interface n'existe pas
                    clazz.Contract =
                        _iLayer.ServiceContracts.Find(
                            delegate(ServiceContract c) { return(c.Name == txtContractName.Text); });

                    if (clazz.Contract == null)
                    {
                        clazz.Contract          = new ServiceContract(clazz.Store);
                        clazz.Contract.RootName = txtRootName.Text;
                        clazz.Layer.LayerPackage.InterfaceLayer.ServiceContracts.Add(clazz.Contract);
                        UnplacedModelHelper.RegisterNewModel(clazz.Store, clazz.Contract);

                        // Si la classe courante utilise un seul contract, on le recopie
                        IList <ClassUsesOperations> links = ClassUsesOperations.GetLinksToServicesUsed(clazz);
                        if (links.Count == 1)
                        {
                            ServiceContract contract = links[0].TargetService as ServiceContract;
                            if (contract != null)
                            {
                                TypeWithOperations.CopyOperations(contract, clazz.Contract);
                            }
                            else
                            {
                                ExternalServiceContract externalContract =
                                    links[0].TargetService as ExternalServiceContract;
                                if (externalContract != null)
                                {
                                    TypeWithOperations.CopyOperations(externalContract.ReferencedServiceContract,
                                                                      clazz.Contract);
                                }
                            }
                        }
                    }
                }

                using (Transaction transaction = elem.Store.TransactionManager.BeginTransaction("Set root name"))
                {
                    // Force la transaction pour que la règle s'execute tout de suite et qu'on puisse
                    // forcer le nom ensuite
                    clazz.Contract.RootName = elem.RootName;
                    transaction.Commit();
                }

                if (clazz.Contract.Name != txtContractName.Text)
                {
                    clazz.Contract.Name = txtContractName.Text;
                }
            }

            e.CancelBubble = true;
        }