public RepositoryEditorViewModel()
 {
     Projects = new ObservableCollection<Project>(GetProjects());
     //ProjectsView.CurrentChanged += OnProjectViewCurrentChanged;
     ProjectItems = new ObservableCollection<ProjectItem>();
     //ProjectItemsView.CurrentChanged += OnProjectItemViewCurrentChanged;
     CodeClasses = new ObservableCollection<CodeClass>();
     //CodeClassesView.CurrentChanged += OnCodeClassViewCurrentChanged;
     RepositoryModel = new RepositoryPoco();
     SetupCommands();
     Version = RepositoryEditorModel.GetVersion();
 }
        public static void MyClassInitialize(TestContext testContext)
        {
            RepositoryPoco repository = new RepositoryPoco
                                            {
                                                DcFullClassName = typeof (TestDataContext).FullName,
                                                RepositoryName = "Test"
                                            };

            EntityPoco entity;
            PropertyPoco property;

            #region Родитель

            repository.Entities.Add(entity = new EntityPoco
                                                 {
                                                     RpName = EntityParentName,
                                                     DcFullName = typeof (Parent).FullName,
                                                 });
            entity.Properties.Add(new PropertyPoco
                                      {
                                          DisplayName = "Parent ID",
                                          DcName = "ParentID",
                                          RpName = "ParentID",
                                          IsPK = true,
                                          NotNull = true,
                                          Type = "System.Guid"
                                      });
            entity.Properties.Add(property = new PropertyPoco
                                      {
                                          DisplayName = "Целое число",
                                          DcName = "Int",
                                          RpName = "Int",
                                          CreateNullable = true,
                                          IsPK = false,
                                          NotNull = true,
                                          Type = "System.Int32",
                                          MinValue = 10,
                                          UseMinValue = true,
                                          MaxValue = 20,
                                          UseMaxValue = true
                                      });
            property.CheckValues.Add(new CheckValuePoco()
                                         {
                                             Value = 13.ToString()
                                         });
            property.CheckValues.Add(new CheckValuePoco()
                                         {
                                             Value = 15.ToString()
                                         });
            //entity.Properties.Add(new PropertyPoco
            //                          {
            //                              DisplayName = "Целое число (nullable)",
            //                              DcName = "NullableInt",
            //                              RpName = "NullableInt",
            //                              IsPK = false,
            //                              NotNull = true,
            //                              Type = "System.Int32?",
            //                              MinValue = 10,
            //                              UseMinValue = true,
            //                              MaxValue = 20,
            //                              UseMaxValue = true
            //                          });

            #endregion

            XmlSerializer ser = new XmlSerializer(typeof (RepositoryPoco));
            string xml;
            using (var sw = new StringWriter())
            {
                ser.Serialize(sw, repository);
                xml = sw.ToString();
            }
            //Компили сборку
            CodeCompileUnit code = GeneratorCore.GenerateCode(xml);
            code.ReferencedAssemblies.Add(typeof (RepositoryBase<,>).Assembly.Location);
            code.ReferencedAssemblies.Add(typeof (IDataErrorInfo).Assembly.Location);
            code.ReferencedAssemblies.Add(typeof (DataContext).Assembly.Location);
            code.ReferencedAssemblies.Add(typeof (Expression).Assembly.Location);
            code.ReferencedAssemblies.Add(typeof (TestDataContext).Assembly.Location);
            code.ReferencedAssemblies.Add(typeof (IDbConnection).Assembly.Location);

            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters param = new CompilerParameters()
                                           {

                                           };
            using (var sw = new StringWriter())
            {
                provider.GenerateCodeFromCompileUnit(
                    code,
                    sw,
                    new CodeGeneratorOptions
                        {
                            BlankLinesBetweenMembers = true,
                            BracingStyle = "C",
                            VerbatimOrder = true
                        });
                _text = sw.ToString();
            }
            CompilerResults results = provider.CompileAssemblyFromDom(param, code);
            if (results.Errors.Count == 0)
                _assembly = results.CompiledAssembly;
        }
        public static void LoadFromDteProjectItem(ProjectItem item, RepositoryPoco model)
        {
            //Помечаем существующие классы и их свойста не валидными
            foreach (EntityPoco entity in model.Entities)
            {
                entity.NotValid = true;
                foreach (PropertyPoco property in entity.Properties)
                    property.NotValid = true;
            }
            List<CodeClass> codeClasses = new List<CodeClass>();
            foreach (CodeElement element in item.FileCodeModel.CodeElements)
                codeClasses.AddRange(GetCodeClass(element));
            // Просматриваем каждый клас объявленный в файле (даже во вложенных namespace и вложенные классы)
            foreach (CodeClass codeClass in codeClasses)
            {
                // Выбираем классы, помеченные атрибутом TableAttribute
                if (codeClass.Attributes.Cast<CodeAttribute>().Any(codeAttribute => codeAttribute.FullName == "System.Data.Linq.Mapping.TableAttribute"))
                {
                    EntityPoco entityPoco = model.Entities.SingleOrDefault(e => e.DcName == codeClass.Name);
                    if (entityPoco != null)
                    {
                        entityPoco.DcFullName = codeClass.FullName;
                        entityPoco.NotValid = false;
                    }
                    else
                    {
                        entityPoco = new EntityPoco
                                         {
                                             DcFullName = codeClass.FullName,
                                             DcName = codeClass.Name,
                                             RpName = codeClass.Name
                                         };
                        model.Entities.Add(entityPoco);
                    }

                    foreach (CodeElement element in codeClass.Children)
                    {
                        if (element.Kind == vsCMElement.vsCMElementProperty)
                        {
                            CodeProperty codeProperty = (CodeProperty) element;
                            CodeAttribute attribute = codeProperty.Attributes.Cast<CodeAttribute>().SingleOrDefault(ca => ca.FullName == "System.Data.Linq.Mapping.ColumnAttribute");
                            if (attribute != null)
                            {
                                bool isNew = false;
                                PropertyPoco propertyPoco = entityPoco.Properties.SingleOrDefault(p => p.DcName == codeProperty.Name);
                                if (propertyPoco != null)
                                {
                                    propertyPoco.Type = codeProperty.Type.CodeType.FullName;
                                    propertyPoco.NotValid = false;
                                }
                                else
                                {
                                    propertyPoco = new PropertyPoco
                                                       {
                                                           DcName = codeProperty.Name,
                                                           RpName = codeProperty.Name,
                                                           Type = codeProperty.Type.CodeType.FullName
                                                       };
                                    entityPoco.Properties.Add(propertyPoco);
                                    isNew = true;
                                }

                                CodeAttributeArgument argument;

                                argument = attribute.Children.Cast<CodeAttributeArgument>().SingleOrDefault(arg => arg.Name == "IsPrimaryKey");
                                if (argument != null)
                                    propertyPoco.IsPK = argument.Value == "true";
                                else
                                    propertyPoco.IsPK = false;

                                argument = attribute.Children.Cast<CodeAttributeArgument>().SingleOrDefault(arg => arg.Name == "DbType");
                                propertyPoco.NotNull = argument != null && argument.Value.ToLower().Contains("not null");

                                if (argument != null)
                                {
                                    int strLen;
                                    if (GetVarCharLength(argument.Value, out strLen))
                                        propertyPoco.StringLength = strLen;
                                }

                                argument = attribute.Children.Cast<CodeAttributeArgument>().SingleOrDefault(arg => arg.Name == "IsDbGenerated");
                                if (argument != null)
                                    propertyPoco.IsCalculate = argument.Value == "true";
                                else
                                    propertyPoco.IsCalculate = false;

                                if (isNew)
                                {
                                    argument = attribute.Children.Cast<CodeAttributeArgument>().SingleOrDefault(arg => arg.Name == "Name");
                                    propertyPoco.DisplayName = argument != null
                                        ? argument.Value.Replace("[", string.Empty).Replace("]", string.Empty).Replace("\"", string.Empty)
                                        : codeProperty.Name.Replace('_', ' ');
                                }
                            }
                        }
                    }
                }
            }
        }
 public static void SaveTo(string fileName, RepositoryPoco model)
 {
     using (var fs = new FileStream(fileName, FileMode.Create))
     {
         XmlSerializer serializer = new XmlSerializer(typeof (RepositoryPoco));
         serializer.Serialize(fs, model);
     }
 }
        private static CodeTypeDeclaration GetDMInterface(RepositoryPoco model)
        {
            CodeTypeDeclaration dm = new CodeTypeDeclaration(GetDataModuleInterfaceName(model.RepositoryName))
                                         {
                                             IsInterface = true,
                                             Attributes = MemberAttributes.Public,
                                             IsPartial = true
                                         };
            dm.BaseTypes.Add(RepositoryDMBaseInterfaceName);

            foreach (EntityPoco entity in model.Entities)
                dm.Members.Add(GetDMInterfaceRepository(entity));

            return dm;
        }
        private static CodeMemberMethod GetDMInit(RepositoryPoco model)
        {
            CodeMemberMethod method = new CodeMemberMethod()
                                          {
                                              Attributes = MemberAttributes.Family | MemberAttributes.Final,
                                              Name = RepositoryDMInitMethodName
                                          };
            CodeMethodInvokeExpression dispose = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), RepositoryDMDisposeMethodName);
            method.Statements.Add(dispose);

            CodeFieldReferenceExpression var = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), RepositoryDMDataContextPropertyName);
            CodeObjectCreateExpression create = new CodeObjectCreateExpression(model.DcFullClassName, new CodeVariableReferenceExpression(RepositoryDMConnectionStringPropertyName));
            method.Statements.Add(new CodeAssignStatement(var, create));

            foreach (EntityPoco entity in model.Entities)
            {
                var = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), GetBackFieldName(GetPluralForm(entity.RpName)));
                create = new CodeObjectCreateExpression(entity.RpName + RepositoryClassNameSuffix,
                                                        new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), RepositoryDMDataContextPropertyName));
                method.Statements.Add(new CodeAssignStatement(var, create));
                method.Statements.Add(
                    new CodeMethodInvokeExpression(
                        new CodeFieldReferenceExpression(
                            new CodeThisReferenceExpression(),
                            RepositoryDMAllRepositoriesPropertyName),
                        "Add",
                        var));
            }

            method.Statements.Add(new CodeMethodInvokeExpression(
                                      new CodeThisReferenceExpression(),
                                      RepositoryDMPartialInitMethodName,
                                      new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), RepositoryDMDataContextPropertyName)));

            return method;
        }
        private static CodeTypeDeclaration GetDM(RepositoryPoco model)
        {
            CodeTypeDeclaration dm = new CodeTypeDeclaration(GetDataModuleName(model.RepositoryName))
                                         {
                                             IsClass = true,
                                             Attributes = MemberAttributes.Public,
                                             IsPartial = true
                                         };
            dm.BaseTypes.Add(RepositoryDMBaseClassName);
            dm.BaseTypes.Add(GetDataModuleInterfaceName(model.RepositoryName));

            dm.Members.Add(GetDMConstructor());
            dm.Members.Add(GetDMConnectionString());
            dm.Members.Add(GetDMConnect());
            dm.Members.Add(GetDMInit(model));

            foreach (EntityPoco entity in model.Entities)
                GetDMRepository(dm, entity);

            dm.Members.Add(GetDMPartialInitMethod());

            return dm;
        }