public ProjectOutputTypes Convert(ProjectTypes projectType)
        {
            Argument.IsNotNull(() => projectType);

            switch (projectType)
            {
                case ProjectTypes.Console:
                    return ProjectOutputTypes.Console;

                case ProjectTypes.WPF:
                    return ProjectOutputTypes.WPF;

                case ProjectTypes.WinForms:
                    return ProjectOutputTypes.WinForms;

                case ProjectTypes.Test:
                    return ProjectOutputTypes.Test;

                case ProjectTypes.Library:
                    return ProjectOutputTypes.Library;

                default:
                    throw new ArgumentOutOfRangeException("projectType");
            }
        }
Пример #2
0
        private TreeNode CreateProjectNode(TreeNode root, SolutionProject project)
        {
            if (this.projectNodes.ContainsKey(project))
            {
                return(projectNodes[project]);
            }

            var parent = root;

            if (project.ParentProject != null)
            {
                parent = CreateProjectNode(root, project.ParentProject);
            }

            var node = new TreeNode(project.Name);

            node.Tag = project;
            var projectType = project.IsFolder ? ProjectType.SolutionFolder : ProjectTypes.Find(project.ProjectTypeId);

            node.ImageKey         = ProjectIcons[projectType];
            node.SelectedImageKey = node.ImageKey;
            parent.Nodes.Add(node);
            this.projectNodes.Add(project, node);
            return(node);
        }
Пример #3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //设置只读权限
                if (Request.QueryString["type"] == "read")
                {
                    btn_submit.Visible = false;
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "message", "$(function(){$('input').attr('readonly', 'readonly');$('select').attr('disabled', 'true');$('textarea').attr('readonly', 'readonly');});", true);
                }

                //专业类别
                ProjectTypes.DataSource     = WebBLL.Tbl_ClassManager.GetTbl_ClassByParentID(56);
                ProjectTypes.DataTextField  = "ClassName";
                ProjectTypes.DataValueField = "ClassName";
                ProjectTypes.DataBind();
                //级别
                ProjectLevel.DataSource     = WebBLL.Tbl_ClassManager.GetTbl_ClassByParentID(58);
                ProjectLevel.DataTextField  = "ClassName";
                ProjectLevel.DataValueField = "ClassName";
                ProjectLevel.DataBind();
                //部门
                Depart.DataSource     = WebBLL.Tbl_ClassManager.GetTbl_ClassByParentID(52);
                Depart.DataTextField  = "ClassName";
                Depart.DataValueField = "ClassName";
                Depart.DataBind();
                Depart.Items.Insert(0, new ListItem("选择部门", ""));

                Bind();
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //项目类别
                ProjectTypes.DataSource     = WebBLL.Tbl_ClassManager.GetTbl_ClassByParentID(56);
                ProjectTypes.DataTextField  = "ClassName";
                ProjectTypes.DataValueField = "ClassName";
                ProjectTypes.DataBind();

                //从项目流程打开该页面时
                int projectid = WebCommon.Public.ToInt(Request.QueryString["ProjectID"]);
                if (projectid > 0)
                {
                    WebModels.Tbl_Project project = WebBLL.Tbl_ProjectManager.GetTbl_ProjectById(projectid);
                    ProjectTypes.Items.Insert(0, new ListItem(project.ProjectTypes, project.ProjectTypes));
                    ProjectID.Items.Insert(0, new ListItem(project.ProjectName, projectid.ToString()));
                    ProjectNo.Value = WebBLL.Tbl_ProjectManager.GetProjectNo(project.ProjectTypes);
                }
                else
                {
                    ProjectTypes.Items.Insert(0, new ListItem("选择类别", ""));
                    ProjectID.Items.Insert(0, new ListItem("选择项目", ""));
                }
            }
        }
Пример #5
0
        public async Task GetProjectTypesAsync_Success()
        {
            // Arrange
            var userId  = 1;
            var session = new Session {
                UserId = userId
            };
            var projectId = 10;
            var types     = new ProjectTypes();
            var mockProjectMetaRepository = new Mock <IProjectMetaRepository>();

            mockProjectMetaRepository.Setup(r => r.GetCustomProjectTypesAsync(projectId, userId)).ReturnsAsync(types);
            var mockServiceLogRepository = new Mock <IServiceLogRepository>();
            var projectMetaController    = new ProjectMetaController(mockProjectMetaRepository.Object, mockServiceLogRepository.Object)
            {
                Request = new HttpRequestMessage()
            };

            projectMetaController.Request.Properties[ServiceConstants.SessionProperty] = session;

            // Act
            var result = await projectMetaController.GetProjectTypesAsync(projectId);

            // Assert
            Assert.AreSame(types, result);
        }
Пример #6
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         //专业类别
         ProjectTypes.DataSource     = WebBLL.Tbl_ClassManager.GetTbl_ClassByParentID(56);
         ProjectTypes.DataTextField  = "ClassName";
         ProjectTypes.DataValueField = "ClassName";
         ProjectTypes.DataBind();
         ProjectTypes.Items.Insert(0, new ListItem("选择类型", ""));
         //级别
         ProjectLevel.DataSource     = WebBLL.Tbl_ClassManager.GetTbl_ClassByParentID(58);
         ProjectLevel.DataTextField  = "ClassName";
         ProjectLevel.DataValueField = "ClassName";
         ProjectLevel.DataBind();
         ProjectLevel.Items.Insert(0, new ListItem("选择级别", ""));
         //部门
         Depart.DataSource     = WebBLL.Tbl_ClassManager.GetTbl_ClassByParentID(52);
         Depart.DataTextField  = "ClassName";
         Depart.DataValueField = "ClassName";
         Depart.DataBind();
         Depart.Items.Insert(0, new ListItem("选择部门", ""));
         ProjectManager.Items.Insert(0, new ListItem("选择负责人", ""));
     }
 }
Пример #7
0
        private void ExecuteDelete(object parameter)
        {
            IMessageBoxService msg        = new MessageBoxService();
            string             title      = "Deleting Project Type";
            string             confirmtxt = "Do you want to delete the selected item";

            if (ProjectTypes.Where(x => x.IsChecked).Count() > 1)
            {
                title      = title + "s";
                confirmtxt = confirmtxt + "s";
            }
            if (msg.ShowMessage(confirmtxt + "?", title, GenericMessageBoxButton.OKCancel, GenericMessageBoxIcon.Question).Equals(GenericMessageBoxResult.OK))
            {
                foreach (ProjectTypeModel si in ProjectTypes)
                {
                    if (si.IsChecked)
                    {
                        if (si.ID > 0)
                        {
                            DeleteProjectType(si.ID);
                        }
                        deleteditems.Add(si);
                    }
                }

                foreach (ProjectTypeModel pm in deleteditems)
                {
                    ProjectTypes.Remove(pm);
                }
                deleteditems.Clear();
                CheckValidation();
            }
            msg = null;
        }
Пример #8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //项目类别
                ProjectTypes.DataSource     = WebBLL.Tbl_ClassManager.GetTbl_ClassByParentID(56);
                ProjectTypes.DataTextField  = "ClassName";
                ProjectTypes.DataValueField = "ClassName";
                ProjectTypes.DataBind();
                ProjectTypes.Items.Insert(0, new ListItem("选择项目类别", ""));
                //级别
                ProjectLevel.DataSource     = WebBLL.Tbl_ClassManager.GetTbl_ClassByParentID(58);
                ProjectLevel.DataTextField  = "ClassName";
                ProjectLevel.DataValueField = "ClassName";
                ProjectLevel.DataBind();
                ProjectLevel.Items.Insert(0, new ListItem("选择项目级别", ""));

                //删除
                if (Request.QueryString["limit"] == "del")
                {
                    string ids   = Request.QueryString["id"].ToString();
                    int    count = WebCommon.Public.DataTableDel("tbl_Project", "id in(" + ids + ")");
                    if (count > 0)
                    {
                        WebCommon.Script.Redirect(WebCommon.Public.GetFromUrl());
                    }
                    else
                    {
                        WebCommon.Script.AlertAndGoBack("删除失败!");
                    }
                }
                //绑定列表
                Bind();
            }
        }
Пример #9
0
        public ProjectOutputTypes Convert(ProjectTypes projectType)
        {
            Argument.IsNotNull(() => projectType);

            switch (projectType)
            {
            case ProjectTypes.Console:
                return(ProjectOutputTypes.Console);

            case ProjectTypes.WPF:
                return(ProjectOutputTypes.WPF);

            case ProjectTypes.WinForms:
                return(ProjectOutputTypes.WinForms);

            case ProjectTypes.Test:
                return(ProjectOutputTypes.Test);

            case ProjectTypes.Library:
                return(ProjectOutputTypes.Library);

            default:
                throw new ArgumentOutOfRangeException("projectType");
            }
        }
Пример #10
0
 public Project(ProjectTypes projectType, string title, string description, string days)
 {
     Title       = title;
     Description = description;
     Days        = days;
     ProjectType = projectType;
 }
Пример #11
0
        public IEnumerable <ProjectViewModel> GetProjects(ProjectTypes type)
        {
            var projects = Mapper
                           .Map <IEnumerable <ProjectEntityModel>, IEnumerable <ProjectViewModel> >
                               (this.context.Projects.Where(p => p.ProjectType == type));

            return(projects);
        }
Пример #12
0
        private bool IsDuplicateType()
        {
            var query = ProjectTypes.GroupBy(x => x.Name.Trim().ToUpper())
                        .Where(g => g.Count() > 1)
                        .Select(y => y.Key)
                        .ToList();

            return(query.Count > 0);
        }
Пример #13
0
 private void ProjectTypes_ItemPropertyChanged(object sender, ItemPropertyChangedEventArgs e)
 {
     if (e.PropertyName != "IsChecked")
     {
         CheckValidation();
         isdirty = true;
     }
     IsSelected = ProjectTypes.Where(x => x.IsChecked).Count() > 0;
 }
Пример #14
0
        public Form1()
        {
            InitializeComponent();

            Operations.DisplayInformationHandler += Operations_DisplayHandler;

            ProjectTypeComboBox.DataSource = ProjectTypes.ProjectTypesList();

            Shown += Form1_Shown;
        }
Пример #15
0
 public void RegisterProjectType(string component, ProjectTypes type)
 {
     if (informations.ContainsKey(component))
     {
         informations[component].ProjectType = type;
     }
     else
     {
         throw new UnknownComponentException(component);
     }
 }
Пример #16
0
        private static string GetProjectContents(
            ProjectTypes projecType,
            SupportedCodeGenerator generator)
        {
            switch (generator)
            {
            case SupportedCodeGenerator.NSwag:
            case SupportedCodeGenerator.NSwagStudio:
                switch (projecType)
                {
                case ProjectTypes.DotNetCoreApp:
                    return(NSwagProjectFileContents.NetCoreApp);

                case ProjectTypes.DotNetStandardLibrary:
                    return(NSwagProjectFileContents.NetStandardLibrary);

                default:
                    throw new ArgumentOutOfRangeException(nameof(projecType), projecType, null);
                }

            case SupportedCodeGenerator.AutoRest:
                switch (projecType)
                {
                case ProjectTypes.DotNetCoreApp:
                    return(AutoRestProjectFileContents.NetCoreApp);

                case ProjectTypes.DotNetStandardLibrary:
                    return(AutoRestProjectFileContents.NetStandardLibrary);

                default:
                    throw new ArgumentOutOfRangeException(nameof(projecType), projecType, null);
                }

            case SupportedCodeGenerator.Swagger:
            case SupportedCodeGenerator.OpenApi:
                switch (projecType)
                {
                case ProjectTypes.DotNetCoreApp:
                    return(SwaggerProjectFileContents.NetCoreApp);

                case ProjectTypes.DotNetStandardLibrary:
                    return(SwaggerProjectFileContents.NetStandardLibrary);

                case ProjectTypes.DotNetFramework:
                    return(SwaggerProjectFileContents.NetFrameworkApp);

                default:
                    throw new ArgumentOutOfRangeException(nameof(projecType), projecType, null);
                }

            default:
                throw new ArgumentOutOfRangeException(nameof(generator), generator, null);
            }
        }
        public MainForm()
        {
            InitializeComponent();

            Operations.DisplayInformationHandler += Operations_DisplayHandler;
            Operations.ExportWebPageFileName      = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "results.html");

            ProjectTypeComboBox.DataSource = ProjectTypes.ProjectTypesList();

            Shown += Form1_Shown;
        }
Пример #18
0
 public BudgetProject()
 {
     this.EndDay = 0x1f;
     this.startDay = 1;
     this.amount = 0;
     this.name = string.Empty;
     this.notes = string.Empty;
     this.projectType = ProjectTypes.Budget;
     this._budgetItems = new EntitySet<BudgetItem>(new System.Action<BudgetItem>(this.attach_ToDo), new System.Action<BudgetItem>(this.detach_ToDo));
     this.ItemType = TinyMoneyManager.Component.ItemType.Expense;
     this._budgetItems.CollectionChanged += new NotifyCollectionChangedEventHandler(this._budgetItems_CollectionChanged);
 }
Пример #19
0
        /// <summary>
        /// Dependent type names of this entity
        /// </summary>
        public void DeleteChildren(DatabaseEntities dbContext)
        {
            foreach (var x in PersonStewardTaxonomyBranches.ToList())
            {
                x.DeleteFull(dbContext);
            }

            foreach (var x in ProjectTypes.ToList())
            {
                x.DeleteFull(dbContext);
            }
        }
Пример #20
0
 private void ExecuteAddNew(object parameter)
 {
     ProjectTypes.Add(new ProjectTypeModel()
     {
         ID          = 0,
         Name        = string.Empty,
         Description = string.Empty,
         Colour      = new SolidColorBrush(Colors.AliceBlue).ToString(),
         IsEnabled   = true,
         IsChecked   = false
     });
     CheckValidation();
 }
Пример #21
0
        private async Task LoadProjectTypesLookupAsync()
        {
            ProjectTypes.Clear();
            ProjectTypes.Add(new NullLookupItem {
                DisplayMember = " - "
            });
            var lookup = await _projectTypeLookupDataService.GetProjectTypeLookupAsync();

            foreach (var lookupItem in lookup)
            {
                ProjectTypes.Add(lookupItem);
            }
        }
 public ProjectTypes Post([FromBody] ProjectTypes projectType)
 {
     try
     {
         projectType.EntityState = DomainModelLibrary.EntityState.Added;
         _projectTypeRepository.AddProjectType(projectType);
     }
     catch (Exception ex)
     {
         //retrurn ex.Message;
     }
     return(projectType);
 }
 public ProjectTypes Put([FromBody] ProjectTypes projectType)
 {
     try
     {
         //projectType.EntityState = DomainModelLibrary.EntityState.Modified;
         //_projectTypeRepository.UpdateProjectType(projectType);
     }
     catch (Exception ex)
     {
         ex.ToString();
     }
     return(projectType);
 }
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         //专业类别
         ProjectTypes.DataSource     = WebBLL.Tbl_ClassManager.GetTbl_ClassByParentID(56);
         ProjectTypes.DataTextField  = "ClassName";
         ProjectTypes.DataValueField = "ClassName";
         ProjectTypes.DataBind();
         ProjectTypes.Items.Insert(0, new ListItem("选择类型", ""));
         ProjectID.Items.Insert(0, new ListItem("选择项目", ""));
         PBL_Time.Text = DateTime.Now.ToString("yyy-MM-dd");
     }
 }
Пример #25
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //项目类别
                ProjectTypes.DataSource     = WebBLL.Tbl_ClassManager.GetTbl_ClassByParentID(56);
                ProjectTypes.DataTextField  = "ClassName";
                ProjectTypes.DataValueField = "ClassName";
                ProjectTypes.DataBind();

                ProjectTypes.Items.Insert(0, new ListItem("选择类别", "0"));
                ProjectID.Items.Insert(0, new ListItem("选择项目", "0"));
            }
        }
Пример #26
0
 /// <summary>
 /// Формирует название базы данных.
 /// </summary>
 /// <param name="str">>Строка, из которой будет сформировано название базы данных. Есть предложение делать его из алиаса проекта.</param>
 /// <param name="umbracoMajorVersion">Версия Umbraco (6 или 7)</param>
 /// <returns></returns>
 public static string MakeDatabaseName(string str, ProjectTypes projectType)
 {
     //имеет смысл называть БД именем, формируемым по правилам алиасов, так оно будет вполне "приличным",
     //кроме того, имя используется в команде создания БД, а ShapeAlias удалит все потенциально опасные символы
     string versionSuffix;
     switch (projectType)
     {
         case ProjectTypes.Umbraco6: versionSuffix = "_u6"; break;
         case ProjectTypes.Umbraco7: versionSuffix = "_u7"; break;
         case ProjectTypes.AdvantShop: versionSuffix = "_as"; break;
         default: versionSuffix = ""; break;
     }
     return ShapeAlias(str) + versionSuffix;
 }
Пример #27
0
        /// <summary>
        /// Active Dependent type names of this object
        /// </summary>
        public List <string> DependentObjectNames()
        {
            var dependentObjects = new List <string>();

            if (PersonStewardTaxonomyBranches.Any())
            {
                dependentObjects.Add(typeof(PersonStewardTaxonomyBranch).Name);
            }

            if (ProjectTypes.Any())
            {
                dependentObjects.Add(typeof(ProjectType).Name);
            }
            return(dependentObjects.Distinct().ToList());
        }
Пример #28
0
 public FileDisassemblerHelper(
     SimpleReflector reflector,
     ProjectTypes projectType,
     string outputDirectory,
     WriteLineDelegate writeLineDelegate,
     SetProgressBarDelegate setProgressBarDelegate,
     IsCancelPendingDelegate isCancelPendingDelegate)
 {
     _reflector               = reflector;
     _projectType             = projectType;
     _outputDirectory         = outputDirectory;
     WriteLine               += writeLineDelegate;
     SetProgressBar          += setProgressBarDelegate;
     _isCancelPendingDelegate = isCancelPendingDelegate;
 }
		public FileDisassemblerHelper(
			SimpleReflector reflector,
            ProjectTypes projectType,
			string outputDirectory,
			WriteLineDelegate writeLineDelegate,
			SetProgressBarDelegate setProgressBarDelegate,
            IsCancelPendingDelegate isCancelPendingDelegate)
		{
            _reflector = reflector;
			_projectType = projectType;
			_outputDirectory = outputDirectory;
			WriteLine += writeLineDelegate;
			SetProgressBar += setProgressBarDelegate;
            _isCancelPendingDelegate = isCancelPendingDelegate;
		}
Пример #30
0
 public NewProjectDialogViewModel()
 {
     ProjectTypeRegistry.TypesChanged += OnProjectsChanged;
     foreach (KeyValuePair <string, ProjectType> typePair in ProjectTypeRegistry.RegisteredTypes)
     {
         if (typePair.Key == typePair.Value.ID)
         {
             if (!ProjectTypes.Contains(typePair.Value))
             {
                 ProjectTypes.Add(typePair.Value);
             }
         }
     }
     ProjectLocation = Workspace.DefaultProjectDirectory;
 }
Пример #31
0
        public Project(string path, string name)
        {
            Path = path;
            Name = name;

            switch (path.Substring(path.LastIndexOf(".")))
            {
            case ".csproj": Type = ProjectTypes.CSharp; break;

            case ".vcxproj": Type = ProjectTypes.CplusPlus; break;

            default:
                break;
            }
        }
        static void Main(string[] args)
        {
            ProjectTypes projecttypes = ProjectTypes.GetProjectTypes();


            SerializationWarmUp();

            // Directory("*.*proj")
            //	*.csproj
            //	*.fsproj
            //	*.vbproj
            //	*.cxproj
            //	?????

            string[] files         = null;
            string   searchPattern = "*proj";

            string path = System.IO.Path.Combine("..", "..", "..", "..", "Templates", "Projects");

            files = System.IO.Directory.GetFiles(path, searchPattern, System.IO.SearchOption.AllDirectories);

            files_with_errors = new List <string>();

            nodes_unknown_total = new Dictionary <string, List <string> >();

            Dictionary <string, Project> projects = new Dictionary <string, Project>();

            foreach (string f in files)
            {
                nodes_unknown = null;

                Project project_loaded = ReadProjectAsync(f).Result;

                projects.Add(f, project_loaded);

                if (null != nodes_unknown)
                {
                    nodes_unknown_total.Add(f, nodes_unknown);
                }
            }

            if (nodes_unknown_total.Keys.Count > 0)
            {
                throw new System.SystemException("Project with unknown node found!");
            }

            return;
        }
        public ProjectTypes Delete(int id)
        {
            ProjectTypes projectType = null;

            try
            {
                projectType             = _projectTypeRepository.GetProjectTypeByID(id);
                projectType.EntityState = DomainModelLibrary.EntityState.Deleted;
                _projectTypeRepository.RemoveProjectType(projectType);
            }
            catch (Exception e)
            {
                // return e.ToString();
            }
            return(projectType);
        }
Пример #34
0
        public static void BuildCSharp(
            ProjectTypes projecType,
            string generatedCode,
            SupportedCodeGenerator generator)
        {
            var path = Path.Combine(Directory.GetCurrentDirectory(), Guid.NewGuid().ToString("N"));

            Directory.CreateDirectory(path);
            var projectFile     = Path.Combine(path, "Project.csproj");
            var projectContents = GetProjectContents(projecType, generator);

            Trace.WriteLine(projectContents);
            File.WriteAllText(projectFile, projectContents);
            File.WriteAllText(Path.Combine(path, "Generated.cs"), generatedCode);
            new ProcessLauncher().Start("dotnet.exe", $"build \"{projectFile}\"");
        }
Пример #35
0
        /// <summary>
        /// Creates a new project.
        /// </summary>
        public void NewProject()
        {
            // Checks for already opened project.
            if(MainFormClass.MainForm.IsProjectOpen)
            {
                if(!CloseProject())
                    return;
            }
            try
            {
                // Gets project file name and initializes project variables.
                if(NewDocumentDialogClass.NewDocumentDialog.ShowNewProjectDialog(MainFormClass.MainForm)==DialogResult.OK)
                {
                    projectFileName=NewDocumentDialogClass.NewDocumentDialog.FullFileName;
                    projectFileStream=new FileStream(projectFileName,FileMode.Create);
                    projectFileStream.Lock(0,projectFileStream.Length);

                    projectName=Path.GetFileNameWithoutExtension(projectFileName);
                    projectType=NewDocumentDialogClass.NewDocumentDialog.ProjectType;
                    projectVersion=megaLibVersion;
                    projectFolder=Path.GetDirectoryName(projectFileName);

                    fileSystemWatcher.Path=projectFolder;

                    projectOptions=new ProjectOptions();

                    #region Project Type Specific Initialization

                    if(projectType==ProjectTypes.MegaBoard_v1)
                    {
                        // SettingNameSpace
                        assemblyNamespace="MegaLib.MegaBoardLib";
                        projectOptions.GCC_Version=GCCVersions.Jan_22_2007;
                        projectOptions.PrintfLibraryType=LibTypes.FloatingPoint;
                        projectOptions.ScanfLibraryType=LibTypes.FloatingPoint;
                        projectOptions.MCU=MCUTypes.ATMEGA128;
                        projectOptions.CrystalFrequency=16000000;
                        projectOptions.OutputFolder="Output";
                        projectOptions.ProgrammingPort="COM1";
                        projectOptions.LinkerFlags="";
                        projectOptions.CompilerFlags="";
                        projectOptions.GenerateListFile=true;
                        projectOptions.GenerateMapFile=true;
                        projectOptions.OptimizationFlags= CompilerOptimizationFlags.None;
                        projectOptions.LinkMathLibrary=true;

                        projectOptions.AllowMCUChange=false;
                        projectOptions.AllowLibTypeChange=false;
                        projectOptions.AllowCrysFreqChange=false;
                        projectOptions.AllowMathLibChange=false;
                        projectOptions.AllowOutputTypeChange=true;

                        TreeNode rootNode=new TreeNode("Megaboard Project",0,0);
                        rootNode.Tag=ProjectTreeItemTypes.ProjectType;
                        projectFilesTree.Nodes.Add(rootNode);
                        TreeNode projectNode=new TreeNode(projectName,1,1);
                        projectNode.Tag=ProjectTreeItemTypes.ProjectName;
                        rootNode.Nodes.Add(projectNode);
                        rootNode.Expand();
                        TreeNode libNode=new TreeNode("Libraries",5,5);
                        libNode.Tag=ProjectTreeItemTypes.Library;
                        projectNode.Nodes.Add(libNode);
                        projectNode.Expand();

                        // Creates a new file main.c .If file already exists then chooses a suitable name.
                        string fileName=projectFolder+@"\Main";
                        int indexNumber=0;
                        if(File.Exists(fileName+".c"))
                            while(File.Exists(fileName+(++indexNumber).ToString()+".c"));
                        if(indexNumber>0)
                            fileName+=indexNumber.ToString();
                        fileName+=".c";
                        System.IO.StreamWriter fileWriter=new StreamWriter(fileName,false,System.Text.Encoding.ASCII);
                        fileWriter.Write("#include\"MegaLib.h\"\nint main()\n{\n MegaLibInit();//Initialization Function\n //Write here\n while(1); //do not remove this line\n}\n");
                        fileWriter.Flush();
                        fileWriter.Close();

                        TreeNode mainFileNode=new TreeNode(Path.GetFileName(fileName),2,2);
                        mainFileNode.Tag=ProjectTreeItemTypes.File;
                        projectNode.Nodes.Add(mainFileNode);
                        MainFormClass.MainForm.OpenFile(fileName);
                        projectFilesTree.SelectedNode=mainFileNode;

                    }
                    else if(projectType==ProjectTypes.ATMega128_Project)
                    {
                        // SettingNameSpace
                        assemblyNamespace="MegaLib.ATMega128Lib";
                        projectOptions.GCC_Version=GCCVersions.Jan_22_2007;
                        projectOptions.PrintfLibraryType=LibTypes.FloatingPoint;
                        projectOptions.ScanfLibraryType=LibTypes.FloatingPoint;
                        projectOptions.MCU=MCUTypes.ATMEGA128;
                        projectOptions.CrystalFrequency=16000000;
                        projectOptions.OutputFolder="Output";
                        projectOptions.ProgrammingPort="COM1";
                        projectOptions.LinkerFlags="";
                        projectOptions.CompilerFlags="";
                        projectOptions.GenerateListFile=true;
                        projectOptions.GenerateMapFile=true;
                        projectOptions.OptimizationFlags= CompilerOptimizationFlags.None;
                        projectOptions.LinkMathLibrary=true;

                        projectOptions.AllowMCUChange=true;
                        projectOptions.AllowLibTypeChange=true;
                        projectOptions.AllowCrysFreqChange=true;
                        projectOptions.AllowMathLibChange=true;
                        projectOptions.AllowOutputTypeChange=true;

                        TreeNode rootNode=new TreeNode("AVR Project",0,0);
                        rootNode.Tag=ProjectTreeItemTypes.ProjectType;
                        projectFilesTree.Nodes.Add(rootNode);
                        TreeNode projectNode=new TreeNode(projectName,1,1);
                        projectNode.Tag=ProjectTreeItemTypes.ProjectName;
                        rootNode.Nodes.Add(projectNode);
                        rootNode.Expand();
                        TreeNode libNode=new TreeNode("Libraries",5,5);
                        libNode.Tag=ProjectTreeItemTypes.Library;
                        projectNode.Nodes.Add(libNode);
                        projectNode.Expand();

                        // Creates a new file main.c .If file already exists then chooses a suitable name.
                        string fileName=projectFolder+@"\Main";
                        int indexNumber=0;
                        if(File.Exists(fileName+".c"))
                            while(File.Exists(fileName+(++indexNumber).ToString()+".c"));
                        if(indexNumber>0)
                            fileName+=indexNumber.ToString();
                        fileName+=".c";
                        System.IO.StreamWriter fileWriter=new StreamWriter(fileName,false,System.Text.Encoding.ASCII);
                        fileWriter.Write("#include\"MegaLib.h\"\nint main()\n{\n MegaLibInit();//Initialization Function\n //Write here\n while(1); //do not remove this line\n}\n");
                        fileWriter.Flush();
                        fileWriter.Close();

                        TreeNode mainFileNode=new TreeNode(Path.GetFileName(fileName),2,2);
                        mainFileNode.Tag=ProjectTreeItemTypes.File;
                        projectNode.Nodes.Add(mainFileNode);
                        MainFormClass.MainForm.OpenFile(fileName);
                        projectFilesTree.SelectedNode=mainFileNode;

                    }

                    #endregion

                    // Enabling file watcher.
                    fileSystemWatcher.EnableRaisingEvents=true;

                    // Init Lists
                    availableLibList.Items.Clear();
                    selectedLibList.Items.Clear();
                    foreach(Type selectedType in libAssembly.GetExportedTypes())
                    {
                        if( selectedType.Namespace==assemblyNamespace && !selectedType.IsEnum)
                        {
                            selectedType.GetProperty("IsIncluded").SetValue(null,false,BindingFlags.SetProperty,null,null,null);
                            availableLibList.Items.Add(selectedType.Name);
                        }
                    }

                    MainFormClass.MainForm.IsProjectOpen=true;
                    MainFormClass.MainForm.Text="MegaIDE - "+projectName+".mbp";

                    RecentDocuments.AddToRecentProjects(projectFileName);
                    MainFormClass.MainForm.UpdateRecentDocumentsList();

                    // Sets the tab page to first page in project options dialog.
                    optionsTree.SelectedNode=optionsTree.Nodes[0].Nodes[0];
                    settingsPages.SelectedIndex=0;

                    // Setting Base static properties.
                    libAssembly.GetType("MegaLib.BaseLib",true,false).GetProperty("CrystalFrequency").SetValue(null,projectOptions.CrystalFrequency,BindingFlags.SetProperty|BindingFlags.Static,null,null,null);
                    libAssembly.GetType("MegaLib.BaseLib",true,false).GetProperty("Microcontroller").SetValue(null,projectOptions.MCU.ToString(),BindingFlags.SetProperty|BindingFlags.Static,null,null,null);

                    ShowOptionsDialog();

                    SaveProject();

                    MainFormClass.MainForm.BringProjectTreeToFront();
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("Error creating new project! "+ex.Message,"MegaIDE",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }
        }
Пример #36
0
 public static void CreateDotGitFiles(DirectoryInfo projectFolder, ProjectTypes projectType)
 {
     CreateDotGitFiles(projectFolder.FullName, projectType);
 }
Пример #37
0
        /// <summary>
        /// Создает нужные .gitignore- и .gitkeep-файлы в проектной папке.
        /// Существующие файлы перезаписываются.
        /// Пути к папкам для помещения в них .gitignore-файлов задаются в .config/configuration/appSettings/add[@key='gitDotGitignoreTargets'].
        /// В этих папках создаются .gitignore-файлы с содержанием
        /// *
        /// !.gitignore
        /// Независимо от этих файлов в проектную папку копируется более полный .gitignore-файл из папки, задаваемой в .config/configuration/appSettings/add[@key='gitSampleDotGitignoreLocation'].
        /// Пути к папкам для помещения в них .gitkeep-файлов задаются в .config/configuration/appSettings/add[@key='gitDotGitkeepTargets'].
        /// Пути должны задаваться относительно проектной папки. Типы слэшей не важны.
        /// </summary>
        /// <param name="projectFolderPath"></param>
        public static void CreateDotGitFiles(string projectFolderPath, ProjectTypes projectType)
        {
            if (!Directory.Exists(projectFolderPath))
            {
                throw new ArgumentException("Папка " + projectFolderPath + " не существует.", "projectFolderPath");
            }

            //копирование файла .gitignore в проектную папку
            var sampleDotGitignoreLocation = WebConfigurationManager.AppSettings["gitSampleDotGitignoreLocation"];
            if (!String.IsNullOrEmpty(sampleDotGitignoreLocation))
            {
                var sampleDotGitignoreFileName = (projectType == ProjectTypes.Umbraco6 || projectType == ProjectTypes.Umbraco7) ? "umbraco" :
                    projectType == ProjectTypes.AdvantShop ? "advShop" : "";
                var sampleDotGitignore = new FileInfo(Path.Combine(sampleDotGitignoreLocation, sampleDotGitignoreFileName + ".gitignore"));
                if (!sampleDotGitignore.Exists && projectType != ProjectTypes.Unknown)
                {
                    //если обрабатывается папка проекта известного типа и не найден примерный файл .gitignore, соответствующий
                    //этому типу, производится поиск примерного файла общего типа .gitignore
                    sampleDotGitignore = new FileInfo(Path.Combine(sampleDotGitignoreLocation, ".gitignore"));
                }
                if (sampleDotGitignore.Exists)
                {
                    sampleDotGitignore.CopyTo(Path.Combine(projectFolderPath, ".gitignore"), true);
                }
            }

            //создание "простых" .gitignore-файлов
            var dotGitignoreTargetsString = WebConfigurationManager.AppSettings["gitDotGitignoreTargets"];
            var dotGitignoreTargets = String.IsNullOrEmpty(dotGitignoreTargetsString) ?
                Enumerable.Empty<string>() :
                dotGitignoreTargetsString.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => ResetSlashes(x).Trim());
            var dotGitignoreContent = "*\r\n!.gitignore";
            foreach (var dotGitignoreTarget in dotGitignoreTargets)
            {
                try
                {
                    var dotGitignorePath = Path.Combine(projectFolderPath, dotGitignoreTarget, ".gitignore");
                    using (var writer = File.CreateText(dotGitignorePath))
                    {
                        writer.Write(dotGitignoreContent);
                    }
                }
                catch
                { }
            }

            var dotGitkeepTargetsString = WebConfigurationManager.AppSettings["gitDotGitkeepTargets"];
            var dotGitkeepTargets = String.IsNullOrEmpty(dotGitkeepTargetsString) ?
                Enumerable.Empty<string>() :
                dotGitkeepTargetsString.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x => ResetSlashes(x).Trim());

            //создание пустых файлов .gitkeep
            foreach (var dotGitkeepTarget in dotGitkeepTargets)
            {
                try
                {
                    var dotGitkeepPath = Path.Combine(projectFolderPath, dotGitkeepTarget, ".gitkeep");
                    using (File.Create(dotGitkeepPath))
                    {
                        //The file is opened with read/write access and must be closed before it can be opened by another application.
                        //Использование using позволяет "полуавтоматически" закрывать поток и файл.
                    }
                }
                catch
                { }
            }
        }
Пример #38
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// This method is called after the user has chosen to import a Paratext project.
		/// Prepare to get the settings for that import by first, making sure there are
		/// Paratext projects on the system, and if there is, loading misc. information
		/// about the projects in order for the user to specify the import settings.
		/// </summary>
		/// <returns>A boolean representing indicating whether or not there were
		/// any Paratext projects found on this computer. True if one or more were
		/// found. Otherwise, false.</returns>
		/// ------------------------------------------------------------------------------------
		private bool PrepareToGetParatextProjectSettings()
		{
			// Make sure the paratext projects can be found on this computer.
			if (!FindParatextProjects())
			{
				ScriptureText = null;
				return false;
			}

			LoadParatextProjectCombos();
			m_projectType = ProjectTypes.Paratext;
			return true;
		}
Пример #39
0
        public static List<string> FilterProjects( string BasePath, List<string> Projects, bool ExistsOnly, ProjectTypes ProjectType )
        {
            if ( Projects == null || Projects.Count <= 0 ) {
                return Projects; // You want nothing, you got it.
            }

            List<string> results = new List<string>();
            foreach ( string projectEntry in Projects ) {
                string project = Path.Combine( BasePath, projectEntry );

                if ( ExistsOnly ) {
                    try {
                        if ( !File.Exists( project ) ) {
                            continue; // It doesn't
                        }
                    } catch ( Exception ) {
                        continue; // It doesn't exist 'cause the path is bogus
                    }
                }

                if ( ProjectType != ProjectTypes.All ) {

                    // If it doesn't exist, we can't check it's type
                    try {
                        if ( !File.Exists( project ) ) {
                            continue; // It doesn't
                        }
                    } catch ( Exception ) {
                        continue; // It doesn't exist 'cause the path is bogus
                    }

                    string text = File.ReadAllText( project );
                    if ( string.IsNullOrEmpty( text ) ) {
                        // An empty project file isn't anything
                        continue;
                    }

                    bool app = ( text.IndexOf( "<OutputType>Exe</OutputType>", StringComparison.InvariantCultureIgnoreCase ) > -1 )
                        || ( text.IndexOf( "<OutputType>WinExe</OutputType>", StringComparison.InvariantCultureIgnoreCase ) > -1 )
                        || ( text.IndexOf( "<ConfigurationType>Application</ConfigurationType>", StringComparison.InvariantCultureIgnoreCase ) > -1 );
                    bool web = ( text.IndexOf( "<Content Include=\"Web.config\"", StringComparison.InvariantCultureIgnoreCase ) > -1 )
                                || ( text.IndexOf( "{349c5851-65df-11da-9384-00065b846f21}", StringComparison.InvariantCultureIgnoreCase ) > -1 ); // Web Application Project
                    bool database = ( text.IndexOf( "\"$(MSBuildExtensionsPath)\\Microsoft\\VisualStudio\\v10.0\\TeamData\\Microsoft.Data.Schema.SqlTasks.targets\"", StringComparison.InvariantCultureIgnoreCase ) > -1 );
                    bool test = ( text.IndexOf( "<Reference Include=\"nunit.framework", StringComparison.InvariantCultureIgnoreCase ) > -1 );

                    switch ( ProjectType ) {
                        case ProjectTypes.All: break; // Everything is fine

                        case ProjectTypes.Endpoint: if ( !app && !web && !test && !database ) { continue; } break;

                        case ProjectTypes.Web: if ( !web ) { continue; } break;

                        case ProjectTypes.App: if ( !app ) { continue; } break;

                        case ProjectTypes.Database: if ( !database ) { continue; } break;

                        case ProjectTypes.Test: if ( !test ) { continue; } break;

                        default: throw new ArgumentOutOfRangeException( "ProjectType" );
                    }

                }

                // We've passed all the tests
                results.Add( project );

            }

            return results;
        }
Пример #40
0
        public static string GetVersionShellByType(ProjectTypes projectType)
        {
            switch (projectType)
            {
                case ProjectTypes.Cs:
                    return CsAssembly;

                case ProjectTypes.Vb:
                    return VbAssembly;

                case ProjectTypes.Cpp:
                    return CppAssembly;

                case ProjectTypes.Fs:
                    return FsAssembly;
            }

            throw new ArgumentException("projectType");
        }
 private void ChooseType(object sender, MouseButtonEventArgs e)
 {
     ProjectType = (ProjectTypes)Enum.Parse(typeof(ProjectTypes), (sender as StackPanel).Tag.ToString());
 }
Пример #42
0
        public static string InsertAssemblyInfoProperty(string fileData, string assemblyInfoPropertyName, string assemblyInfoPropertyValue, ProjectTypes projectType)
        {
            var fileDataOut = new StringBuilder();

            var versionShell = GetVersionShellByType(projectType);

            // if working with F# files, remove the "do binding" so we can make sure that the "do" is at the end of the file)
            //if (projectType == ProjectTypes.Fs)
            //{
            //    var regex = new Regex(FsDoRegex);
            //    fileData = regex.Replace(fileData, "");
            //}

            fileDataOut.Append(fileData);

            var versionLine = String.Format(versionShell, assemblyInfoPropertyName, assemblyInfoPropertyValue);

            fileDataOut.AppendLine();
            fileDataOut.Append(versionLine);
            fileDataOut.AppendLine();

            //// for F#, put the do() binding back in
            //if (projectType == ProjectTypes.Fs)
            //{
            //    fileDataOut.Append(FsDoStatement);
            //    fileDataOut.AppendLine();
            //}

            return fileDataOut.ToString();
        }
Пример #43
0
        /// <summary>
        /// Opens a project from a project file.
        /// </summary>
        /// <param name="fileName">
        /// Path of the project file.
        /// </param>
        public void OpenProject(string fileName)
        {
            //Checking for already opened project.
            if(MainFormClass.MainForm.IsProjectOpen)
            {
                if(fileName.ToLower()==projectFileName.ToLower())
                {
                    MessageBox.Show("The project is already open!","MegaIDE",MessageBoxButtons.OK,MessageBoxIcon.Information);
                    return;
                }

                if(!CloseProject())
                    return;
            }

            ArrayList openFilesList=new ArrayList(5);
            isProjectModified=false;
            try
            {
                projectFileName=fileName;
                projectFileStream=new FileStream(projectFileName,FileMode.Open);
                projectFileStream.Lock(0,projectFileStream.Length);
                projectFolder=Path.GetDirectoryName(fileName);

                //Deserializing saved variables.
                BinaryFormatter deserializer=new BinaryFormatter();
                deserializer.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
                deserializer.TypeFormat = System.Runtime.Serialization.Formatters.FormatterTypeStyle.TypesWhenNeeded;

                projectName=(string)deserializer.Deserialize(projectFileStream);
                string projectTypeString=(string)deserializer.Deserialize(projectFileStream);
                projectType=(ProjectTypes)Enum.Parse(typeof(ProjectTypes),projectTypeString);
                projectVersion=(string)deserializer.Deserialize(projectFileStream);

                // Loading Project Tree
                ArrayList treeNodesList = (ArrayList)deserializer.Deserialize(projectFileStream);
                foreach (TreeNode treeNode in treeNodesList)
                {
                    projectFilesTree.Nodes.Add(treeNode);
                }

                openFilesList=(ArrayList)deserializer.Deserialize(projectFileStream);
                projectOptions=(ProjectOptions)deserializer.Deserialize(projectFileStream);
                projectOptions.GCC_Version = projectOptions.GCC_Version;
                if (projectVersion!=megaLibVersion)
                {
                    if(MessageBox.Show("The project has been created using MegaLib version "+projectVersion.Substring(0,3)+" . It will be changed to the current version ( "+megaLibVersion.Substring(0,3)+" ) .Would you like to continue ?","MegaIDE",MessageBoxButtons.YesNo,MessageBoxIcon.Warning)==DialogResult.No)
                    {
                        MainFormClass.MainForm.ClearLibraries();
                        if(projectFilesTree.Nodes.Count != 0)
                        {
                            MainFormClass.MainForm.CloseProjectFiles();
                            projectFilesTree.Nodes.Clear();
                        }
                        try
                        {
                            projectFileStream.Close();
                        }
                        catch{}
                        MainFormClass.MainForm.IsProjectOpen=false;
                        return;
                    }
                    else
                    {
                        projectVersion=megaLibVersion;
                        isProjectModified=true;
                    }
                }
                libList=(ArrayList)deserializer.Deserialize(projectFileStream);

                // SetAssemblyNameSpace
                if(projectType==ProjectTypes.MegaBoard_v1)
                    assemblyNamespace="MegaLib.MegaBoardLib";
                else if(projectType==ProjectTypes.ATMega128_Project)
                    assemblyNamespace="MegaLib.ATMega128Lib";

                // Setting Base static properties.
                libAssembly.GetType("MegaLib.BaseLib",true,false).GetProperty("CrystalFrequency").SetValue(null,projectOptions.CrystalFrequency,BindingFlags.SetProperty|BindingFlags.Static,null,null,null);
                libAssembly.GetType("MegaLib.BaseLib",true,false).GetProperty("Microcontroller").SetValue(null,projectOptions.MCU.ToString(),BindingFlags.SetProperty|BindingFlags.Static,null,null,null);

                // Loading available libraries
                availableLibList.Items.Clear();
                selectedLibList.Items.Clear();
                foreach(object selectedObject in libList)
                {
                    selectedLibList.Items.Add(selectedObject.GetType().Name);
                }
                foreach(Type selectedType in libAssembly.GetExportedTypes())
                {
                    if(selectedType.Namespace==assemblyNamespace && !selectedType.IsEnum)
                    {
                        if(selectedLibList.Items.Contains(selectedType.Name))
                        {
                            selectedType.GetProperty("IsIncluded").SetValue(null,true,BindingFlags.SetProperty|BindingFlags.Static,null,null,null);
                        }
                        else
                        {
                            availableLibList.Items.Add(selectedType.Name);
                            selectedType.GetProperty("IsIncluded").SetValue(null,false,BindingFlags.SetProperty|BindingFlags.Static,null,null,null);
                        }
                    }
                }

                MainFormClass.MainForm.PopulateLibraries(libList);
                fileSystemWatcher.Path=projectFolder;
                fileSystemWatcher.EnableRaisingEvents=true;
            }
            catch(SerializationException)
            {
                // Code to run in case of invalid file
                MainFormClass.MainForm.ClearLibraries();
                if(projectFilesTree.Nodes.Count != 0)
                {
                    MainFormClass.MainForm.CloseProjectFiles();
                    projectFilesTree.Nodes.Clear();
                    libList.Clear();
                }
                MessageBox.Show("Error opening project! The path may not be correct or the file could be corrupt.","MegaIDE",MessageBoxButtons.OK,MessageBoxIcon.Error);
                try
                {
                    projectFileStream.Close();
                }
                catch{}
                MainFormClass.MainForm.IsProjectOpen=false;
                return;
            }
            catch(Exception ex)
            {
                // Code to run in case of invalid file
                MainFormClass.MainForm.ClearLibraries();
                if(projectFilesTree.Nodes.Count != 0)
                {
                    MainFormClass.MainForm.CloseProjectFiles();
                    projectFilesTree.Nodes.Clear();
                }
                MessageBox.Show("Error opening project! "+ex.Message,"MegaIDE",MessageBoxButtons.OK,MessageBoxIcon.Error);
                try
                {
                    projectFileStream.Close();
                }
                catch{}
                MainFormClass.MainForm.IsProjectOpen=false;
                return;
            }

            //Checking for missing files
            ArrayList missingFilesList=new ArrayList(20);
            ArrayList missingNodesList=new ArrayList(20);
            CheckMissingFiles(projectFilesTree.Nodes[0].Nodes[0],missingFilesList,missingNodesList);

            if(missingFilesList.Count != 0)
            {
                if(ExitDialogClass.ExitDialog.ShowMissingFilesDialog(MainFormClass.MainForm,missingFilesList)==DialogResult.Cancel)
                {
                    projectFilesTree.Nodes.Clear();
                    MainFormClass.MainForm.ClearLibraries();
                    ExitDialogClass.ExitDialog.RestoreSettings();
                    return;
                }
                ExitDialogClass.ExitDialog.RestoreSettings();

                //Remove the missing files from the opened files list and tree.
                ArrayList fileNamesToRemove=new ArrayList(3);
                foreach(TreeNode fileNode in missingNodesList)
                {
                    if(openFilesList.Count != 0)
                    {
                        foreach(string openFileName in openFilesList)
                        {
                            if((projectFolder+"\\"+openFileName).ToLower().StartsWith(GetAbsolutePath(fileNode).ToLower()))
                                fileNamesToRemove.Add(openFileName);
                        }
                    }
                    fileNode.Remove();
                }
                foreach(string fileNameToRemove in fileNamesToRemove)
                {
                    openFilesList.Remove(fileNameToRemove);
                }
                isProjectModified=true;
            }
            if(isProjectModified)
            {
                SaveProject();
            }
            MainFormClass.MainForm.IsProjectOpen=true;
            isProjectModified=false;
            if(openFilesList.Count != 0)
                MainFormClass.MainForm.OpenProjectFiles(projectFolder,openFilesList);

            NewDocumentDialogClass.NewDocumentDialog.DialogMode=NewDocumentDialogClass.DialogModes.None;
            MainFormClass.MainForm.Text="MegaIDE - "+projectName+".mbp";
            RecentDocuments.AddToRecentProjects(projectFileName);
            MainFormClass.MainForm.UpdateRecentDocumentsList();
            projectFilesTree.ExpandAll();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileData">AssemblyInfo file contents as a string</param>
        /// <param name="propertyName">Name of the property to modify or insert</param>
        /// <param name="propertyValue">New value of the property</param>
        /// <param name="projectType">Type of project (cs, vb, cpp or fs)</param>
        /// <param name="forceCreate">If the value isn't in the AssemblyInfo file do we insert it anyway</param>
        /// <returns>The updated file data</returns>
        public static string UpdateAssemblyValue(string fileData, string propertyName, string propertyValue, ProjectTypes projectType, bool forceCreate)
        {
            string newFileData;

            // Set up RegEx
            var regExExpression = string.Format(VersioningHelper.RegExPropertyMatch, propertyName);
            var regex = new Regex(regExExpression);

            // perform the actual replacement
            var groups = regex.Match(fileData).Groups;

            // AssemblyInfo Property not found so insert it if forceCreate is true
            // 5 is the number of groups that will be discovered in the regex expression match
            if ((groups.Count < 5) && (forceCreate))
            {
                newFileData = VersioningHelper.InsertAssemblyInfoProperty(fileData, propertyName, propertyValue, projectType);
            }
            else
            {
                // Property was found...replace the value
                var replacementString = string.Format("{0}{1}{2}", groups["PropertyPrefix"], propertyValue, groups["PropertyPostfix"]);

                newFileData = regex.Replace(fileData, replacementString);
            }

            return newFileData;
        }
 /// <summary>
 /// Creates the vs project item.
 /// </summary>
 /// <param name="project">The project.</param>
 /// <returns>return vs project it</returns>
 private static VsProjectItem CreateVsProjectItem(ProjectTypes.Project project)
 {
     var proToRet = new VsProjectItem();
     proToRet.ProjectName = project.Name;
     proToRet.ProjectFilePath = project.Path;
     return proToRet;
 }
Пример #46
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// This method is called after the user has chosen to import a non Paratext project
		/// (e.g. a standard format project). Prepare to get the settings for that import.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		private void PrepareToGetOtherProjectSettings()
		{
			m_projectType = ProjectTypes.Other;
			ScriptureText = null;
		}
Пример #47
0
 public void RegisterProjectType( string component, ProjectTypes type )
 {
     if( informations.ContainsKey( component ) ) {
         informations[component].ProjectType = type;
     } else {
         throw new UnknownComponentException( component );
     }
 }
        private static string SetupAssemblyInfo(ProjectTypes projectType)
        {
            switch (projectType)
            {
                case ProjectTypes.Cs:
                    return "\r\n[assembly: AssemblyInformationalVersion(\"This is some info\")]\r\n";

                case ProjectTypes.Vb:
                    return "\r\n<Assembly: AssemblyInformationalVersion(\"This is some info\")>\r\n";

                case ProjectTypes.Cpp:
                    return "\r\n[assembly: AssemblyInformationalVersionAttribute(\"This is some info\")];\r\n";

                case ProjectTypes.Fs:
                    return "\r\n[<assembly: AssemblyInformationalVersion(\"This is some info\")>]\r\n";

            }

            throw new MSTestInvalidArgumentException();
        }
        /// <summary>
        /// Walks through the list of provided AssemblyInfo properties and updates those values 
        /// </summary>
        /// <param name="filePath">AssemblyInfo file being modified</param>
        /// <param name="assemblyInfoProperties">List of properties and values to change</param>
        /// <param name="buildDetail"></param>
        /// <param name="buildDate"></param>
        /// <param name="projectType">Type of project (cs, vb, cpp or fs)</param>
        /// <param name="forceCreate">If the value isn't in the AssemblyInfo file do we insert it anyway</param>
        /// <param name="workspace"></param>
        /// <param name="buildAgent"></param>
        /// <param name="buildNumberPrefix"></param>
        /// <param name="incrementBy"></param>
        /// <param name="buildNumberSeed"></param>
        public ICollection<KeyValuePair<string, string>> UpdateAssemblyValues(string filePath, IList<KeyValuePair<string, string>> assemblyInfoProperties,
            IBuildDetail buildDetail, DateTime buildDate, ProjectTypes projectType, bool forceCreate, Workspace workspace, IBuildAgent buildAgent, int buildNumberPrefix, int incrementBy, int buildNumberSeed)
        {
            var convertedValues = new List<KeyValuePair<string, string>>();
            var newFileData = new StringBuilder();

            // make sure you can write to the file
            var currentFileAttributes = File.GetAttributes(filePath);
            File.SetAttributes(filePath, currentFileAttributes & ~FileAttributes.ReadOnly);

            // Get the file data
            var fileData = File.ReadAllText(filePath);

            // if working with F# files, remove the "do binding" so we can make sure that the "do" is at the end of the file
            if (projectType == ProjectTypes.Fs)
            {
                var regex = new Regex(@".*(\(\s*\)|do\s*\(\s*\))");
                fileData = regex.Replace(fileData, "");
            }

            foreach (KeyValuePair<string, string> property in assemblyInfoProperties)
            {
                string convertedValue = VersioningHelper.ReplacePatternsInPropertyValue(property.Value, buildDetail, buildNumberPrefix, incrementBy, buildNumberSeed,
                                                                                        buildDate, workspace, buildAgent);

                convertedValues.Add(new KeyValuePair<string, string>(property.Key, convertedValue));

                fileData = UpdateAssemblyValue(fileData, property.Key, convertedValue, projectType, forceCreate);
            }

            // do we need to put a NewLine char in the data from the file
            if (DoesLastLineContainCr(fileData))
            {
                newFileData.Append(fileData);
            }
            else
            {
                newFileData.AppendLine(fileData);
            }

            // for F#, put the do() binding back in
            if (projectType == ProjectTypes.Fs)
            {
                newFileData.AppendLine("do ()");
            }

            // Write the data out to a file
            File.WriteAllText(filePath, newFileData.ToString());

            // restore the file's original attributes
            File.SetAttributes(filePath, currentFileAttributes);

            return convertedValues;
        }