Example #1
1
        public void CreateFolders(Project currentProject, string schedule, string projectName, string relativePath)
        {
            //Create a File under Properties Folder which will contain information about all WebJobs
            //https://github.com/ligershark/webjobsvs/issues/6

            // Check if the WebApp is C# or VB
            string dir = GetProjectDirectory(currentProject);
            var propertiesFolderName = "Properties";
            if (currentProject.CodeModel.Language == CodeModelLanguageConstants.vsCMLanguageVB)
            {
                propertiesFolderName = "My Project";
            }

            DirectoryInfo info = new DirectoryInfo(Path.Combine(dir, propertiesFolderName));

            string readmeFile = Path.Combine(info.FullName, "WebJobs.xml");

            // Copy File if it does not exit
            if (!File.Exists(readmeFile))
                AddReadMe(readmeFile);

            //Add a WebJob info to it
            XDocument doc = XDocument.Load(readmeFile);
            XElement root = new XElement("WebJob");
            root.Add(new XAttribute("Project", projectName));
            root.Add(new XAttribute("RelativePath", relativePath));
            root.Add(new XAttribute("Schedule", schedule));
            doc.Element("WebJobs").Add(root);
            doc.Save(readmeFile);
            currentProject.ProjectItems.AddFromFile(readmeFile);
        }
 public GenerateTypeOptionsResult(
     Accessibility accessibility,
     TypeKind typeKind,
     string typeName,
     Project project,
     bool isNewFile,
     string newFileName,
     IList<string> folders,
     string fullFilePath,
     Document existingDocument,
     bool areFoldersValidIdentifiers,
     bool isCancelled = false)
 {
     this.Accessibility = accessibility;
     this.TypeKind = typeKind;
     this.TypeName = typeName;
     this.Project = project;
     this.IsNewFile = isNewFile;
     this.NewFileName = newFileName;
     this.Folders = folders;
     this.FullFilePath = fullFilePath;
     this.ExistingDocument = existingDocument;
     this.AreFoldersValidIdentifiers = areFoldersValidIdentifiers;
     this.IsCancelled = isCancelled;
 }
Example #3
0
        public static ServiceProvider CreateTestServices(
            IServiceProvider applicationServices,
            Project project,
            ReportingChannel channel)
        {
            var services = new ServiceProvider(applicationServices);

            var loggerFactory = new LoggerFactory();
            loggerFactory.AddProvider(new TestHostLoggerProvider(channel));
            services.Add(typeof(ILoggerFactory), loggerFactory);

            var libraryExporter = applicationServices.GetRequiredService<ILibraryExporter>();
            var export = libraryExporter.GetExport(project.Name);

            var projectReference = export.MetadataReferences
                .OfType<IMetadataProjectReference>()
                .Where(r => r.Name == project.Name)
                .FirstOrDefault();

            services.Add(
                typeof(ISourceInformationProvider),
                new SourceInformationProvider(projectReference, loggerFactory.CreateLogger<SourceInformationProvider>()));

            services.Add(typeof(ITestDiscoverySink), new TestDiscoverySink(channel));
            services.Add(typeof(ITestExecutionSink), new TestExecutionSink(channel));

            return services;
        }
Example #4
0
        protected PackagesProviderBase(
            Project project,
            IProjectManager projectManager,
            ResourceDictionary resources,
            ProviderServices providerServices,
            IProgressProvider progressProvider)
        {
            if (projectManager == null) {
                throw new ArgumentNullException("projectManager");
            }

            if (project == null) {
                throw new ArgumentNullException("project");
            }

            if (resources == null) {
                throw new ArgumentNullException("resources");
            }

            if (providerServices == null) {
                throw new ArgumentNullException("providerServices");
            }

            _progressProvider = progressProvider;
            _resources = resources;
            _scriptExecutor = providerServices.ScriptExecutor;
            _progressWindowOpener = providerServices.ProgressWindow;
            _outputConsole = new Lazy<IConsole>(() => providerServices.OutputConsoleProvider.CreateOutputConsole(requirePowerShellHost: false));
            ProjectManager = projectManager;
            _project = project;
        }
 /// <summary>
 /// Constructor for the class for Epi 2000 projects
 /// </summary>
 /// <param name="proj">Project the metadata belongs to</param>
 public MetadataDbProvider(Project proj)
 {
     IDbDriverFactory dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.AccessDriver);
     OleDbConnectionStringBuilder cnnStrBuilder = new OleDbConnectionStringBuilder();
     cnnStrBuilder.DataSource = proj.FilePath;
     this.db = dbFactory.CreateDatabaseObject(cnnStrBuilder);
 }
        public void TestUndoRedoCommand()
        {
            // Arrange
            var project = new Project();
            var context = new BlockCommandContext(project);
            ProjectBlockCollection blocks = project.Blocks;
            Block block = blocks[0];
            using (block.AcquireBlockLock(RequestLock.Write))
            {
                block.SetText("abcd");
            }
            int blockVersion = block.Version;
            BlockKey blockKey = block.BlockKey;

            var command = new InsertTextCommand(new BlockPosition(blockKey, 2), "YES");
            project.Commands.Do(command, context);
            project.Commands.Undo(context);

            // Act
            project.Commands.Redo(context);

            // Assert
            Assert.AreEqual(1, blocks.Count);
            Assert.AreEqual(
                new BlockPosition(blocks[0], 5), project.Commands.LastPosition);

            const int index = 0;
            Assert.AreEqual("abYEScd", blocks[index].Text);
            Assert.AreEqual(blockVersion + 3, blocks[index].Version);
        }
Example #7
0
        public DteProject(Project project)
        {
            DteObject = project;

            _openWrapEnabled = Lazy.Is(() => MSBuildProject.OpenWrapEnabled(project.FullName), true);
            _file = Lazy.Is(() => LocalFileSystem.Instance.GetFile(project.FullName));
        }
 public void SetGenerateTypeOptions(
     Accessibility accessibility = Accessibility.NotApplicable,
     TypeKind typeKind = TypeKind.Class,
     string typeName = null,
     Project project = null,
     bool isNewFile = false,
     string newFileName = null,
     IList<string> folders = null,
     string fullFilePath = null,
     Document existingDocument = null,
     bool areFoldersValidIdentifiers = true,
     string defaultNamespace = null,
     bool isCancelled = false)
 {
     Accessibility = accessibility;
     TypeKind = typeKind;
     TypeName = typeName;
     Project = project;
     IsNewFile = isNewFile;
     NewFileName = newFileName;
     Folders = folders;
     FullFilePath = fullFilePath;
     ExistingDocument = existingDocument;
     AreFoldersValidIdentifiers = areFoldersValidIdentifiers;
     DefaultNamespace = defaultNamespace;
     IsCancelled = isCancelled;
 }
        internal DatabaseGenerationAssemblyLoader(Project project, string vsInstallPath)
        {
            _assembliesInstalledUnderVisualStudio = new Dictionary<string, string>();
            // For these DLLs we should use the version pre-installed under the VS directory,
            // not whatever reference the project may have
            _assembliesInstalledUnderVisualStudio.Add(
                "ENTITYFRAMEWORK", Path.Combine(vsInstallPath, "EntityFramework.dll"));
            _assembliesInstalledUnderVisualStudio.Add(
                "ENTITYFRAMEWORK.SQLSERVER", Path.Combine(vsInstallPath, "EntityFramework.SqlServer.dll"));
            _assembliesInstalledUnderVisualStudio.Add(
                "ENTITYFRAMEWORK.SQLSERVERCOMPACT", Path.Combine(vsInstallPath, "EntityFramework.SqlServerCompact.dll"));

            _projectReferenceLookup = new Dictionary<string, Reference3>();
            _websiteReferenceLookup = new Dictionary<string, AssemblyReference>();
            if (project != null)
            {
                var vsProject = project.Object as VSProject2;
                var vsWebSite = project.Object as VSWebSite;
                if (vsProject != null)
                {
                    _isWebsite = false;
                    CacheProjectReferences(vsProject);
                }
                else if (vsWebSite != null)
                {
                    _isWebsite = true;
                    CacheWebsiteReferences(vsWebSite);
                }
            }
        }
Example #10
0
    public static void Main(string[] args)
    {
        try
        {
            Project project =
                new Project("My Product",

                    new Dir(@"%ProgramFiles%\My Company\My Product",
                        new File(@"AppFiles\MyApp.exe",
                            new FileShortcut("MyApp", @"%Desktop%") { Advertise = true }),
                        new ExeFileShortcut("Uninstall MyApp", "[System64Folder]msiexec.exe", "/x [ProductCode]")),

                    new Dir(@"%ProgramMenu%\My Company\My Product",
                        new ExeFileShortcut("Uninstall MyApp", "[System64Folder]msiexec.exe", "/x [ProductCode]")));

            project.GUID = new Guid("6fe30b47-2577-43ad-9095-1861ba25889b");
            project.UI = WUI.WixUI_ProgressOnly;
            project.OutFileName = "setup";

            Compiler.BuildMsi(project);
        }
        catch (System.Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
        public ProjectBindingOperation(IServiceProvider serviceProvider, Project project, ISolutionRuleStore ruleStore)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            if (project == null)
            {
                throw new ArgumentNullException(nameof(project));
            }

            if (ruleStore == null)
            {
                throw new ArgumentNullException(nameof(ruleStore));
            }

            this.serviceProvider = serviceProvider;
            this.initializedProject = project;
            this.ruleStore = ruleStore;

            this.sourceControlledFileSystem = this.serviceProvider.GetService<ISourceControlledFileSystem>();
            this.sourceControlledFileSystem.AssertLocalServiceIsNotNull();

            this.ruleSetSerializer = this.serviceProvider.GetService<IRuleSetSerializer>();
            this.ruleSetSerializer.AssertLocalServiceIsNotNull();
        }
Example #12
0
        public async Task<ICallHierarchyMemberItem> CreateItem(ISymbol symbol,
            Project project, IEnumerable<Location> callsites, CancellationToken cancellationToken)
        {
            if (symbol.Kind == SymbolKind.Method ||
                symbol.Kind == SymbolKind.Property ||
                symbol.Kind == SymbolKind.Event ||
                symbol.Kind == SymbolKind.Field)
            {
                symbol = GetTargetSymbol(symbol);

                var finders = await CreateFinders(symbol, project, cancellationToken).ConfigureAwait(false);

                ICallHierarchyMemberItem item = new CallHierarchyItem(symbol,
                    project.Id,
                    finders,
                    () => symbol.GetGlyph().GetImageSource(GlyphService),
                    this,
                    callsites,
                    project.Solution.Workspace);

                return item;
            }

            return null;
        }
Example #13
0
        public static async Task<int> Execute(
            IServiceProvider services, 
            Project project,
            string command,
            string[] args)
        {
            var environment = (IApplicationEnvironment)services.GetService(typeof(IApplicationEnvironment));
            var commandText = project.Commands[command];
            var replacementArgs = CommandGrammar.Process(
                commandText, 
                (key) => GetVariable(environment, key),
                preserveSurroundingQuotes: false)
                .ToArray();

            var entryPoint = replacementArgs[0];
            args = replacementArgs.Skip(1).Concat(args).ToArray();

            if (string.IsNullOrEmpty(entryPoint) ||
                string.Equals(entryPoint, "run", StringComparison.Ordinal))
            {
                entryPoint = project.EntryPoint ?? project.Name;
            }

            CallContextServiceLocator.Locator.ServiceProvider = services;
            return await ExecuteMain(services, entryPoint, args);
        }
 private void ProjectRemoved(Project project)
 {
     if (project.Name == ProjectHelpers.SolutionItemsFolder)
     {
         DeleteSolutionSettings();
     }
 }
 public static void CompileProject(Project project)
 {
     if (project != null && !string.IsNullOrEmpty(project.FullName))
     {
         Task.Run(() => Compile(project));
     }
 }
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);

            // ExStart:RenderResourceUsageView
            // Create project instance
            Project project1 = new Project(dataDir + "ResourceUsageView.mpp");
                        
            // Define the SaveOptions with required TimeScale settings as Days
            SaveOptions options = new PdfSaveOptions();
            options.Timescale = Timescale.Days;

            // Set the Presentation format to ResourceUsage
            options.PresentationFormat = PresentationFormat.ResourceUsage;

            // Save the Project
            string outputFile = "result_ResourceUsageView_days_out.pdf";
            project1.Save(dataDir + outputFile, options);

            // Set the Tiemscale settings to ThirdsOfMonths and save the Project
            options.Timescale = Timescale.ThirdsOfMonths;
            outputFile = "result_ResourceUsageView_thirdsOfMonths_out.pdf";
            project1.Save(dataDir + outputFile, options);

            // Set the Timescale settings to Months and save the Project
            options.Timescale = Timescale.Months;
            outputFile = "result_ResourceUsageView_months_out.pdf";
            project1.Save(dataDir + outputFile, options);
            // ExEnd:RenderResourceUsageView
        }
Example #17
0
        public FrmProjectSettings(Project project)
            : this()
        {
            Project = project ?? new Project();

            InitializeControls();
        }
 public void AddProject(Project project)
 {
     if (ProjectAdded != null)
     {
         ProjectAdded(this, new ProjectEventArgs(project));
     }
 }
        public override async Task SynchronizeWithBuildAsync(Project project, ImmutableArray<DiagnosticData> diagnostics)
        {
            if (!PreferBuildErrors(project.Solution.Workspace))
            {
                // prefer live errors over build errors
                return;
            }

            using (var poolObject = SharedPools.Default<HashSet<string>>().GetPooledObject())
            {
                var lookup = CreateDiagnosticIdLookup(diagnostics);

                foreach (var stateSet in _stateManager.GetStateSets(project))
                {
                    var descriptors = HostAnalyzerManager.GetDiagnosticDescriptors(stateSet.Analyzer);
                    var liveDiagnostics = ConvertToLiveDiagnostics(lookup, descriptors, poolObject.Object);

                    // we are using Default so that things like LB can't use cached information
                    var projectTextVersion = VersionStamp.Default;
                    var semanticVersion = await project.GetDependentSemanticVersionAsync(CancellationToken.None).ConfigureAwait(false);

                    var state = stateSet.GetState(StateType.Project);
                    var existingDiagnostics = await state.TryGetExistingDataAsync(project, CancellationToken.None).ConfigureAwait(false);

                    var mergedDiagnostics = MergeDiagnostics(liveDiagnostics, GetExistingDiagnostics(existingDiagnostics));
                    await state.PersistAsync(project, new AnalysisData(projectTextVersion, semanticVersion, mergedDiagnostics), CancellationToken.None).ConfigureAwait(false);
                    RaiseDiagnosticsUpdated(StateType.Project, project.Id, stateSet, new SolutionArgument(project), mergedDiagnostics);
                }
            }
        }
      internal static bool CanGenerateHandleCodeProperty(string testClassFixturePostFix, CodeClass parentCodeClass, CodeProperty codeProperty, Project unitTestProject)
      {
         foreach (ProjectItem projectItem in unitTestProject.ProjectItems)
         {
            List<CodeClass> lstProjectCodeClasses = UTGManagerAndExaminor.ProjectItemExaminor.GetCodeClasses(projectItem.FileCodeModel);

            foreach (CodeClass codeClass in lstProjectCodeClasses)
            {
               if ((parentCodeClass.Name + testClassFixturePostFix).Equals(codeClass.Name))
               {
                  foreach (CodeElement codeElement in codeClass.Members)
                  {
                     if (codeElement is CodeProperty)
                     {
                        if (codeProperty.Name.Equals(((CodeProperty)codeElement).Name))
                           return false;

                     }
                  }
               }
            }
         }

         return true;
      }
        public static IProjectSystem CreateProjectSystem(Project project)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            if (String.IsNullOrEmpty(project.FullName))
            {
                throw new InvalidOperationException(
                    String.Format(CultureInfo.CurrentCulture,
                    VsResources.DTE_ProjectUnsupported, project.GetName()));
            }

            // Try to get a factory for the project type guid            
            foreach (var guid in project.GetProjectTypeGuids())
            {
                Func<Project, IProjectSystem> factory;
                if (_factories.TryGetValue(guid, out factory))
                {
                    return factory(project);
                }
            }

            // Fall back to the default if we have no special project types
            return new VsProjectSystem(project);
        }
        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (dictionary != null)
            {
                var project = new Project();

                project.Id = dictionary.GetValue<int>(RedmineKeys.ID);
                project.Description = dictionary.GetValue<string>(RedmineKeys.DESCRIPTION);
                project.HomePage = dictionary.GetValue<string>(RedmineKeys.HOMEPAGE);
                project.Name = dictionary.GetValue<string>(RedmineKeys.NAME);
                project.Identifier = dictionary.GetValue<string>(RedmineKeys.IDENTIFIER);
                project.Status = dictionary.GetValue<ProjectStatus>(RedmineKeys.STATUS);
                project.CreatedOn = dictionary.GetValue<DateTime?>(RedmineKeys.CREATED_ON);
                project.UpdatedOn = dictionary.GetValue<DateTime?>(RedmineKeys.UPDATED_ON);
                project.Trackers = dictionary.GetValueAsCollection<ProjectTracker>(RedmineKeys.TRACKERS);
                project.CustomFields = dictionary.GetValueAsCollection<IssueCustomField>(RedmineKeys.CUSTOM_FIELDS);
                project.IsPublic = dictionary.GetValue<bool>(RedmineKeys.IS_PUBLIC);
                project.Parent = dictionary.GetValueAsIdentifiableName(RedmineKeys.PARENT);
                project.IssueCategories = dictionary.GetValueAsCollection<ProjectIssueCategory>(RedmineKeys.ISSUE_CATEGORIES);
                project.EnabledModules = dictionary.GetValueAsCollection<ProjectEnabledModule>(RedmineKeys.ENABLED_MODULES);
                return project;
            }

            return null;
        }
Example #23
0
 public override void CheckSanity(Project project, Whee.WordBuilder.ProjectV2.IProjectSerializer serializer)
 {
     if (_Position == 0)
     {
         serializer.Warn("The capitalize command requires the first argument to be a non-zero integer.", this);
     }
 }
 private void UpdateForProject(Project project)
 {
     if (lastStatuses.ContainsKey(project.Url) && lastCompletedStatuses.ContainsKey(project.Url))
     {
         if (lastStatuses[project.Url].IsInProgress)
         {
             if (project.StatusValue == BuildStatusEnum.Successful)
             {
                 if (BuildStatusUtils.IsErrorBuild(lastCompletedStatuses[project.Url]))
                 {
                     FixedProjects.Add(project);
                 }
                 else
                 {
                     SucceedingProjects.Add(project);
                 }
             }
             else if (TreatAsFailure(project.Status))
             {
                 if (TreatAsFailure(lastCompletedStatuses[project.Url]))
                 {
                     StillFailingProjects.Add(project);
                 }
                 else
                 {
                     FailingProjects.Add(project);
                 }
             }
         }
     }
 }
		public void Initialize(
			Project project,
			ProjectFolder projectFolder)
		{
			_project = project;
			_projectFolder = projectFolder;
		}
        private static async Task<ImmutableArray<INavigateToSearchResult>> FindNavigableDeclaredSymbolInfosAsync(
            Project project, Document searchDocument, string pattern, CancellationToken cancellationToken)
        {
            var containsDots = pattern.IndexOf('.') >= 0;
            using (var patternMatcher = new PatternMatcher(pattern, allowFuzzyMatching: true))
            {
                var result = ArrayBuilder<INavigateToSearchResult>.GetInstance();
                foreach (var document in project.Documents)
                {
                    if (searchDocument != null && document != searchDocument)
                    {
                        continue;
                    }

                    cancellationToken.ThrowIfCancellationRequested();
                    var declarationInfo = await document.GetSyntaxTreeIndexAsync(cancellationToken).ConfigureAwait(false);

                    foreach (var declaredSymbolInfo in declarationInfo.DeclaredSymbolInfos)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        var patternMatches = patternMatcher.GetMatches(
                            GetSearchName(declaredSymbolInfo),
                            declaredSymbolInfo.FullyQualifiedContainerName,
                            includeMatchSpans: true);

                        if (!patternMatches.IsEmpty)
                        {
                            result.Add(ConvertResult(containsDots, declaredSymbolInfo, document, patternMatches));
                        }
                    }
                }

                return result.ToImmutableAndFree();
            }
        }
        // Generates all of the Web Forms Pages (Default Insert, Edit, Delete),
        private void AddStorageContexts(
            Project project,
            string selectionRelativePath,
            string dbContextNamespace,
            string dbContextTypeName,
            CodeType modelType,
            bool useMasterPage,
            string masterPage = null,
            bool overwriteViews = true
        )
        {
            if (modelType == null)
            {
                throw new ArgumentNullException("modelType");
            }

            var webForms = new[] { "StorageContext", "StorageContext.KeyHelpers" };

            // Now add each view
            foreach (string webForm in webForms)
            {
                AddStorageContextTemplates(
                    selectionRelativePath: selectionRelativePath,
                    modelType: modelType,
                    dbContextNamespace: dbContextNamespace,
                    dbContextTypeName: dbContextTypeName,
                    webFormsName: webForm,
                    overwrite: overwriteViews);
            }
        }
        public static void Run()
        {
            try
            {
                // ExStart:MPPFileUpdate
                // The path to the documents directory.
                string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName);

                // Read an existing project
                Project project = new Project(dataDir + "MPPFileUpdate.mpp");

                // Create a new task
                Task task = project.RootTask.Children.Add("Task1");

                task.Set(Tsk.Start, new DateTime(2012, 8, 1));
                task.Set(Tsk.Finish, new DateTime(2012, 8, 5));

                // Save the project as MPP project file
                project.Save(dataDir + "AfterLinking_out.Mpp", SaveFileFormat.MPP);
                // ExEnd:MPPFileUpdate   
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http://www.aspose.com/purchase/default.aspx.");
            }            
        }
Example #29
0
        private static string GetProjectDirectory(Project project)
        {
            if (project.Object is VSLangProj.VSProject)
                return Path.GetDirectoryName(project.FullName);

            return project.Properties.Item("fullPath").Value.ToString();
        }
        private async Task <IProjectMetric> PerformReview(Project project)
        {
            var results = await _calculator.Calculate(project, null).ConfigureAwait(false);

            return(results);
        }
Example #31
0
 public static VirtualOrderContainer <ProjectField> GetFieldsContainer(
     this Project field)
 => VirtualOrderContainerFacade.Create(field.ProjectFields, field.ProjectFieldsOrdering);
Example #32
0
        public int InsertProjectInfoDb(Project objProjectInfoBlob)
        {
            int val = 0;


            SqlString = "INSERT into ProjectInfo (SystemID,ProjectID,ProjectName,ActiveFlag,LastUpdateDate,Version,DBVersion,Measure,Location,SoldTo,ShipTo,OrderNo,ContractNo,Region,Office,Engineer,YINO,DeliveryDate,OrderDate,Remarks,ProjectType,Vendor,ProjectBlob,SystemBlob,SQBlob) Values(@SystemID, @ProjectID,@ProjectName,@ActiveFlag,@LastUpdateDate,@Version,@DBVersion,@Measure,@Location,@SoldTo,@ShipTo,@OrderNo,@ContractNo,@Region,@Office, @Engineer, @YINO,@DeliveryDate, @OrderDate,@Remarks,@ProjectType, @Vendor, @ProjectBlob,@SystemBlob,@SqBlob)";

            byte[]          ProjectBlob = null;
            MemoryStream    objstream   = new MemoryStream();
            BinaryFormatter bf          = new BinaryFormatter();

            bf.Serialize(objstream, objProjectInfoBlob);
            ProjectBlob = objstream.ToArray();

            JCHVRF.Model.New.Project objProjectInfo = new JCHVRF.Model.New.Project();

            #region SaveDataInDb

            try
            {
                using (OleDbConnection conn = new OleDbConnection(connectionString))

                {
                    using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))

                    {
                        conn.Open();
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.AddWithValue("@SystemID", objProjectInfoBlob.objProjectInfo.SystemID);
                        cmd.Parameters.AddWithValue("@ProjectID", 10);
                        cmd.Parameters.AddWithValue("@ProjectName", objProjectInfoBlob.objProjectInfo.ProjectName);
                        cmd.Parameters.AddWithValue("@ActiveFlag", 1);
                        cmd.Parameters.AddWithValue("@LastUpdateDate", DateTime.Now.Date);
                        cmd.Parameters.AddWithValue("@Version", objProjectInfoBlob.objProjectInfo.Version);
                        cmd.Parameters.AddWithValue("@DBVersion", objProjectInfoBlob.objProjectInfo.DBVersion);
                        cmd.Parameters.AddWithValue("@Measure", objProjectInfoBlob.objProjectInfo.Measure);
                        cmd.Parameters.AddWithValue("@Location", objProjectInfoBlob.objProjectInfo.Location);
                        cmd.Parameters.AddWithValue("@SoldTo", objProjectInfoBlob.objProjectInfo.SoldTo);
                        cmd.Parameters.AddWithValue("@ShipTo", objProjectInfoBlob.objProjectInfo.ShipTo);
                        cmd.Parameters.AddWithValue("@OrderNo", objProjectInfoBlob.objProjectInfo.OrderNo);
                        cmd.Parameters.AddWithValue("@ContractNo", objProjectInfoBlob.objProjectInfo.ContractNo);
                        cmd.Parameters.AddWithValue("@Region", objProjectInfoBlob.objProjectInfo.Region);
                        cmd.Parameters.AddWithValue("@Office", objProjectInfoBlob.objProjectInfo.Office);
                        cmd.Parameters.AddWithValue("@Engineer", objProjectInfoBlob.objProjectInfo.Engineer);
                        cmd.Parameters.AddWithValue("@YINO", objProjectInfoBlob.objProjectInfo.YINo);
                        cmd.Parameters.AddWithValue("@DeliveryDate", DateTime.Now.Date);
                        cmd.Parameters.AddWithValue("@OrderDate", DateTime.Now.Date);
                        cmd.Parameters.AddWithValue("@Remarks", objProjectInfoBlob.objProjectInfo.Remarks);
                        cmd.Parameters.AddWithValue("@ProjectType", objProjectInfoBlob.objProjectInfo.ProjectType);
                        cmd.Parameters.AddWithValue("@Vendor", objProjectInfoBlob.objProjectInfo.Vendor);
                        cmd.Parameters.AddWithValue("@ProjectBlob", ProjectBlob);
                        cmd.Parameters.AddWithValue("@SystemBlob", DbType.Binary);
                        cmd.Parameters.AddWithValue("@SqBlob", DbType.Binary);
                        val = cmd.ExecuteNonQuery();
                        conn.Close();
                    }
                }
            }


            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            return(val);
        }
Example #33
0
 public ProjectItemsFake(Project containingProject)
 {
     this.ContainingProject = containingProject;
 }
Example #34
0
        /// <summary>
        /// Gets the config from file.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        private static string GetConfigFromFile(string key)
        {
            Grid grid = m_Site.Component as Grid;

            if (grid == null)
            {
                throw new GridException("Could not get Grid");
            }
            if (grid.WebConfigAppSettings != null)
            {
                if (grid.NextConfigCheck < System.DateTime.Now)
                {
                    return(GetConfigSetting(grid, key));
                }
                grid.NextConfigCheck = System.DateTime.Now.AddSeconds(5);
                return(GetConfigSetting(grid, grid.WebConfigFile, key));
            }
            DTE devenv = (DTE)m_Site.GetService(typeof(DTE));

            if (devenv == null)
            {
                MessageBox.Show("Error Message: No design time environment was detected.");
                return(null);
            }

            Array projects = (Array)devenv.ActiveSolutionProjects;

            if (projects.Length == 0)
            {
                MessageBox.Show("Error Message: No Projects found in your designer environment. (Your IDE contains 0 active projects)");
                return(null);
            }
            // go through the items of the project to find the configuration
            Project project = (Project)(projects.GetValue(0));

            foreach (ProjectItem item in project.ProjectItems)
            {
                // if it is the configuration, then open it up
                if (string.Compare(item.Name, "web.config", true) != 0)
                {
                    continue;
                }
                FileInfo info = new FileInfo("/");

                IWebApplication webApp = (IWebApplication)m_Site.GetService(typeof(IWebApplication));
                if (webApp != null)
                {
                    IProjectItem appitem = webApp.GetProjectItemFromUrl("~/web.config");
                    if (appitem.PhysicalPath == null)
                    {
                        MessageBox.Show(string.Format("Error Message: '{0}' has no physical path.", appitem.Name));
                        return(null);
                    }
                    info = new FileInfo(appitem.PhysicalPath);
                }
                else
                {
                    MessageBox.Show("Web Application Design Host is unavailable.");
                }
                if (info.Directory != null)
                {
                    if (System.IO.File.Exists(String.Format("{0}\\{1}", info.Directory.FullName, item.Name)) ==
                        false)
                    {
                        MessageBox.Show(
                            string.Format("Error Message: '{0}\\{1}' does not exists.", info.Directory.FullName,
                                          item.Name));
                        return(null);
                    }
                }

                if (info.Directory == null)
                {
                    continue;
                }
                string val = GetConfigSetting(grid, String.Format("{0}\\{1}", info.Directory.FullName, item.Name), key);
                if (val != null)
                {
                    return(val);
                }
            }

            return(null);
        }
Example #35
0
        private static bool HasReferenceTo(IAssemblySymbol containingAssembly, Project sourceProject, Project project, CancellationToken cancellationToken)
        {
            if (containingAssembly == null)
            {
                throw new ArgumentNullException(nameof(containingAssembly));
            }

            if (project == null)
            {
                throw new ArgumentNullException(nameof(project));
            }

            if (sourceProject != null)
            {
                // most of time, compilation should be already there
                return(project.ProjectReferences.Any(p => p.ProjectId == sourceProject.Id));
            }

            // If the project we're looking at doesn't even support compilations, then there's no
            // way for it to have an IAssemblySymbol.  And without that, there is no way for it
            // to have any sort of 'ReferenceTo' the provided 'containingAssembly' symbol.
            if (!project.SupportsCompilation)
            {
                return(false);
            }

            // WORKAROUND:
            // perf  check metadata reference using newly created empty compilation with only metadata references.
            var compilation = project.LanguageServices.CompilationFactory.CreateCompilation(
                project.AssemblyName,
                project.CompilationOptions);

            compilation = compilation.AddReferences(project.MetadataReferences);

            return(project.MetadataReferences.Any(m =>
            {
                var symbol = compilation.GetAssemblyOrModuleSymbol(m) as IAssemblySymbol;
                return symbol != null && symbol.Name == containingAssembly.Name;
            }));
        }
Example #36
0
        private static async Task AddNonSubmissionDependentProjectsAsync(IAssemblySymbol sourceAssembly, Solution solution, Project sourceProject, HashSet <DependentProject> dependentProjects, CancellationToken cancellationToken)
        {
            var isSubmission = sourceProject != null && sourceProject.IsSubmission;

            if (isSubmission)
            {
                return;
            }

            var internalsVisibleToMap = CreateInternalsVisibleToMap(sourceAssembly);

            SymbolKey sourceAssemblySymbolKey = null;

            // TODO(cyrusn): What about error tolerance situations.  Do we maybe want to search
            // transitive dependencies as well?  Even if the code wouldn't compile, they may be
            // things we want to find.
            foreach (var projectId in solution.ProjectIds)
            {
                var project = solution.GetProject(projectId);

                cancellationToken.ThrowIfCancellationRequested();

                if (HasReferenceTo(sourceAssembly, sourceProject, project, cancellationToken))
                {
                    bool hasInternalsAccess = false;
                    if (internalsVisibleToMap.Value.Contains(project.AssemblyName))
                    {
                        var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);

                        var targetAssembly = compilation.Assembly;
                        if (sourceAssembly.Language != targetAssembly.Language)
                        {
                            sourceAssemblySymbolKey = sourceAssemblySymbolKey ?? sourceAssembly.GetSymbolKey();
                            var sourceAssemblyInTargetCompilation = sourceAssemblySymbolKey.Resolve(compilation, cancellationToken: cancellationToken).Symbol as IAssemblySymbol;

                            if (sourceAssemblyInTargetCompilation != null)
                            {
                                hasInternalsAccess = targetAssembly.IsSameAssemblyOrHasFriendAccessTo(sourceAssemblyInTargetCompilation);
                            }
                        }
                        else
                        {
                            hasInternalsAccess = targetAssembly.IsSameAssemblyOrHasFriendAccessTo(sourceAssembly);
                        }
                    }

                    dependentProjects.Add(new DependentProject(project.Id, hasInternalsAccess));
                }
            }
        }
Example #37
0
        private static async Task AddSubmissionDependentProjectsAsync(Solution solution, Project sourceProject, HashSet <DependentProject> dependentProjects, CancellationToken cancellationToken)
        {
            var isSubmission = sourceProject != null && sourceProject.IsSubmission;

            if (!isSubmission)
            {
                return;
            }

            var projectIdsToReferencingSubmissionIds = new Dictionary <ProjectId, List <ProjectId> >();

            // search only submission project
            foreach (var projectId in solution.ProjectIds)
            {
                var project = solution.GetProject(projectId);
                if (project.IsSubmission && project.SupportsCompilation)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    // If we are referencing another project, store the link in the other direction
                    // so we walk across it later
                    var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);

                    if (compilation.PreviousSubmission != null)
                    {
                        var referencedProject = solution.GetProject(compilation.PreviousSubmission.Assembly, cancellationToken);
                        List <ProjectId> referencingSubmissions = null;

                        if (!projectIdsToReferencingSubmissionIds.TryGetValue(referencedProject.Id, out referencingSubmissions))
                        {
                            referencingSubmissions = new List <ProjectId>();
                            projectIdsToReferencingSubmissionIds.Add(referencedProject.Id, referencingSubmissions);
                        }

                        referencingSubmissions.Add(project.Id);
                    }
                }
            }

            // Submission compilations are special. If we have submissions 0, 1 and 2 chained in
            // the natural way, and we have a symbol in submission 0, we need to search both 1
            // and 2, even though 2 doesn't have a direct reference to 1. Hence we need to take
            // our current set of projects and find the transitive closure over backwards
            // submission previous references.
            var projectIdsToProcess = new Stack <ProjectId>(dependentProjects.Select(dp => dp.ProjectId));

            while (projectIdsToProcess.Count > 0)
            {
                var toProcess = projectIdsToProcess.Pop();

                if (projectIdsToReferencingSubmissionIds.ContainsKey(toProcess))
                {
                    foreach (var pId in projectIdsToReferencingSubmissionIds[toProcess])
                    {
                        if (!dependentProjects.Any(dp => dp.ProjectId == pId))
                        {
                            dependentProjects.Add(new DependentProject(pId, hasInternalsAccess: true));
                            projectIdsToProcess.Push(pId);
                        }
                    }
                }
            }
        }
Example #38
0
        public async Task <List <Project> > GetProjectsForUserAsync(User user)
        {
            var requests = CreateUserHasAccessRequests(user);

            // wait for all tasks to complete
            Task <bool[]> aggregateTask = Task.WhenAll(requests.Select(_ => _.Task));

            try
            {
                await aggregateTask;
            }
            catch (Exception exception)
            {
                _logger.LogWarning(exception, "Error on aggregate request");
            }

            List <Project> projects = new List <Project>();

            foreach (var request in requests)
            {
                Project project = projects.SingleOrDefault(_ => _.Id == request.Configuration.Id);
                if (project == null)
                {
                    project = new Project
                    {
                        Id        = request.Configuration.Id,
                        Name      = request.Configuration.Name,
                        Resources = new List <ProjectResourceStatus>()
                    };

                    projects.Add(project);
                }

                var task = request.Task;

                if (task.IsCompletedSuccessfully)
                {
                    _logger.LogDebug("Request to {Project} for {Resource} completed successfully",
                                     new { request.Configuration.Name, request.Configuration.Id },
                                     new { request.Resource.Type, request.Resource.Resource });

                    bool userHasAccess = task.Result;
                    project.Resources.Add(new ProjectResourceStatus
                    {
                        Type   = request.Resource.Type.ToString(),
                        Status = userHasAccess
                            ? ProjectResourceStatuses.Member
                            : ProjectResourceStatuses.NotMember
                    });
                }
                else if (task.IsFaulted)
                {
                    Guid   requestId = Guid.NewGuid();
                    string message   = $"Unknown error executing request id {requestId}";

                    if (task.Exception != null)
                    {
                        // log with exception
                        _logger.LogError(task.Exception, "Request to get user {User} access status on project {Project} for resource {Resource} failed ({RequestId}",
                                         new { user.Id, user.UserName, user.UserPrincipalName },
                                         new { request.Configuration.Name, request.Configuration.Id },
                                         new { request.Resource.Type, request.Resource.Resource, request.Resource.BaseAddress },
                                         requestId);
                    }
                    else
                    {
                        // log without exception
                        _logger.LogError("Request to get user {User} access status on project {Project} for resource {Resource} failed ({RequestId}",
                                         new { user.Id, user.UserName, user.UserPrincipalName },
                                         new { request.Configuration.Name, request.Configuration.Id },
                                         new { request.Resource.Type, request.Resource.Resource },
                                         requestId);
                    }

                    project.Resources.Add(new ProjectResourceStatus {
                        Type = request.Resource.Type.ToString(), Status = ProjectResourceStatuses.Error, Message = message
                    });
                }
            }

            return(projects);
        }
Example #39
0
 public static IReadOnlyList <ProjectField> GetOrderedFields(this Project field)
 => field.GetFieldsContainer().OrderedItems;
 /// <summary>
 /// Returns the repository name for the given student/project.
 /// </summary>
 public string GetRepoName(Project project, ClassroomMembership student)
 {
     return($"{project.Name}_{student.GitHubTeam}");
 }
Example #41
0
 public IEnumerable <IDomainEntityStateDecorator> GetDecorators()
 {
     return(_decorators ?? (_decorators = Project.ResolveDecorators(this)));
 }
Example #42
0
        public async Task MvcTemplate_IndividualAuth(bool useLocalDB)
        {
            Project = await ProjectFactory.GetOrCreateProject("mvcindividual" + (useLocalDB ? "uld" : ""), Output);

            var createResult = await Project.RunDotNetNewAsync("mvc", auth : "Individual", useLocalDB : useLocalDB);

            Assert.True(0 == createResult.ExitCode, ErrorMessages.GetFailedProcessMessage("create/restore", Project, createResult));

            var projectFileContents = Project.ReadFile($"{Project.ProjectName}.csproj");

            if (!useLocalDB)
            {
                Assert.Contains(".db", projectFileContents);
            }

            var publishResult = await Project.RunDotNetPublishAsync();

            Assert.True(0 == publishResult.ExitCode, ErrorMessages.GetFailedProcessMessage("publish", Project, publishResult));

            // Run dotnet build after publish. The reason is that one uses Config = Debug and the other uses Config = Release
            // The output from publish will go into bin/Release/netcoreappX.Y/publish and won't be affected by calling build
            // later, while the opposite is not true.

            var buildResult = await Project.RunDotNetBuildAsync();

            Assert.True(0 == buildResult.ExitCode, ErrorMessages.GetFailedProcessMessage("build", Project, buildResult));

            var migrationsResult = await Project.RunDotNetEfCreateMigrationAsync("mvc");

            Assert.True(0 == migrationsResult.ExitCode, ErrorMessages.GetFailedProcessMessage("run EF migrations", Project, migrationsResult));
            Project.AssertEmptyMigration("mvc");

            var pages = new List <Page> {
                new Page
                {
                    Url   = PageUrls.ForgotPassword,
                    Links = new string [] {
                        PageUrls.HomeUrl,
                        PageUrls.RegisterUrl,
                        PageUrls.LoginUrl,
                        PageUrls.HomeUrl,
                        PageUrls.PrivacyUrl,
                        PageUrls.PrivacyUrl
                    }
                },
                new Page
                {
                    Url   = PageUrls.HomeUrl,
                    Links = new string[] {
                        PageUrls.HomeUrl,
                        PageUrls.RegisterUrl,
                        PageUrls.LoginUrl,
                        PageUrls.HomeUrl,
                        PageUrls.PrivacyUrl,
                        PageUrls.DocsUrl,
                        PageUrls.PrivacyUrl
                    }
                },
                new Page
                {
                    Url   = PageUrls.PrivacyFullUrl,
                    Links = new string[] {
                        PageUrls.HomeUrl,
                        PageUrls.RegisterUrl,
                        PageUrls.LoginUrl,
                        PageUrls.HomeUrl,
                        PageUrls.PrivacyUrl,
                        PageUrls.PrivacyUrl
                    }
                },
                new Page
                {
                    Url   = PageUrls.LoginUrl,
                    Links = new string[] {
                        PageUrls.HomeUrl,
                        PageUrls.RegisterUrl,
                        PageUrls.LoginUrl,
                        PageUrls.HomeUrl,
                        PageUrls.PrivacyUrl,
                        PageUrls.ForgotPassword,
                        PageUrls.RegisterUrl,
                        PageUrls.ResendEmailConfirmation,
                        PageUrls.ExternalArticle,
                        PageUrls.PrivacyUrl
                    }
                },
                new Page
                {
                    Url   = PageUrls.RegisterUrl,
                    Links = new string [] {
                        PageUrls.HomeUrl,
                        PageUrls.RegisterUrl,
                        PageUrls.LoginUrl,
                        PageUrls.HomeUrl,
                        PageUrls.PrivacyUrl,
                        PageUrls.ExternalArticle,
                        PageUrls.PrivacyUrl
                    }
                }
            };

            using (var aspNetProcess = Project.StartBuiltProjectAsync())
            {
                Assert.False(
                    aspNetProcess.Process.HasExited,
                    ErrorMessages.GetFailedProcessMessageOrEmpty("Run built project", Project, aspNetProcess.Process));

                await aspNetProcess.AssertPagesOk(pages);
            }

            using (var aspNetProcess = Project.StartPublishedProjectAsync())
            {
                Assert.False(
                    aspNetProcess.Process.HasExited,
                    ErrorMessages.GetFailedProcessMessageOrEmpty("Run published project", Project, aspNetProcess.Process));

                await aspNetProcess.AssertPagesOk(pages);
            }
        }
Example #43
0
        private async Task MvcTemplateCore(string languageOverride)
        {
            Project = await ProjectFactory.GetOrCreateProject("mvcnoauth" + (languageOverride == "F#" ? "fsharp" : "csharp"), Output);

            var createResult = await Project.RunDotNetNewAsync("mvc", language : languageOverride);

            Assert.True(0 == createResult.ExitCode, ErrorMessages.GetFailedProcessMessage("create/restore", Project, createResult));

            var projectExtension    = languageOverride == "F#" ? "fsproj" : "csproj";
            var projectFileContents = Project.ReadFile($"{Project.ProjectName}.{projectExtension}");

            Assert.DoesNotContain(".db", projectFileContents);
            Assert.DoesNotContain("Microsoft.EntityFrameworkCore.Tools", projectFileContents);
            Assert.DoesNotContain("Microsoft.VisualStudio.Web.CodeGeneration.Design", projectFileContents);
            Assert.DoesNotContain("Microsoft.EntityFrameworkCore.Tools.DotNet", projectFileContents);
            Assert.DoesNotContain("Microsoft.Extensions.SecretManager.Tools", projectFileContents);

            // Avoid the F# compiler. See https://github.com/dotnet/aspnetcore/issues/14022
            if (languageOverride != null)
            {
                return;
            }

            var publishResult = await Project.RunDotNetPublishAsync();

            Assert.True(0 == publishResult.ExitCode, ErrorMessages.GetFailedProcessMessage("publish", Project, publishResult));

            // Run dotnet build after publish. The reason is that one uses Config = Debug and the other uses Config = Release
            // The output from publish will go into bin/Release/netcoreappX.Y/publish and won't be affected by calling build
            // later, while the opposite is not true.

            var buildResult = await Project.RunDotNetBuildAsync();

            Assert.True(0 == buildResult.ExitCode, ErrorMessages.GetFailedProcessMessage("build", Project, buildResult));

            IEnumerable <string> menuLinks = new List <string> {
                PageUrls.HomeUrl,
                PageUrls.HomeUrl,
                PageUrls.PrivacyFullUrl
            };

            var footerLinks = new string[] { PageUrls.PrivacyFullUrl };

            var pages = new List <Page>
            {
                new Page
                {
                    Url   = PageUrls.HomeUrl,
                    Links = menuLinks.Append(PageUrls.DocsUrl).Concat(footerLinks)
                },
                new Page
                {
                    Url   = PageUrls.PrivacyFullUrl,
                    Links = menuLinks.Concat(footerLinks)
                }
            };

            using (var aspNetProcess = Project.StartBuiltProjectAsync())
            {
                Assert.False(
                    aspNetProcess.Process.HasExited,
                    ErrorMessages.GetFailedProcessMessageOrEmpty("Run built project", Project, aspNetProcess.Process));

                await aspNetProcess.AssertPagesOk(pages);
            }

            using (var aspNetProcess = Project.StartPublishedProjectAsync())
            {
                Assert.False(
                    aspNetProcess.Process.HasExited,
                    ErrorMessages.GetFailedProcessMessageOrEmpty("Run published project", Project, aspNetProcess.Process));

                await aspNetProcess.AssertPagesOk(pages);
            }
        }
 public abstract Solution UpgradeProject(Project project, string version);
 private bool CanUpgrade(Project project, string language, string version)
 {
     return(project.Language == language && IsUpgrade(project.ParseOptions, version));
 }
        public Task TransformAsync(XDocument projectFile, DirectoryInfo projectFolder, Project definition)
        {
            XNamespace nsSys      = "http://schemas.microsoft.com/developer/msbuild/2003";
            var        itemGroups = projectFile
                                    .Element(nsSys + "Project")
                                    .Elements(nsSys + "ItemGroup");

            var compileManualIncludes = FindNonWildcardMatchedFiles(projectFolder, itemGroups, "*.cs", nsSys + "Compile");
            var otherIncludes         = itemsToProject.SelectMany(x => itemGroups.Elements(nsSys + x));

            var otherNodes = compileManualIncludes
                             .Where(i => !i.Elements().Any(IsDependent))
                             .RenameAttribute("Include", "Update")
                             .ToList();

            var generatedNodes = compileManualIncludes
                                 .Where(i => i.Elements().SingleOrDefault(IsDependent) != null)
                                 .GroupBy(i => i.Elements().SingleOrDefault(IsDependent).Value)
                                 .Select(e => XElementExtensions.CreateNode(
                                             "Compile",
                                             new[] { new XAttribute("Update", CreateGeneratedAttrValue(e.Attributes())) },
                                             new[] { e.Elements().FirstOrDefault(IsDependent) }))
                                 .ToList();

            definition.ItemsToInclude =
                otherIncludes
                .RenameAttribute("Include", "Update")
                .RenameNode("Content", "None")
                .Concat(otherNodes)
                .Concat(generatedNodes)
                .ToList();

            return(Task.CompletedTask);
        }
Example #47
0
 public FtpConnection(Project parentProject) : base(parentProject)
 {
 }
Example #48
0
        public async Task PinvokeMethodReferences_VB()
        {
            var tree = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText(
                @"
Module Module1
        Declare Function CreateDirectory Lib ""kernel32"" Alias ""CreateDirectoryA"" (ByVal lpPathName As String) As Integer
 
        Private prop As Integer
        Property Prop1 As Integer
            Get
                Return prop
            End Get
            Set(value As Integer)
                CreateDirectory(""T"")  ' Method Call 1
                prop = value
                prop = Nothing
            End Set
        End Property

        Sub Main()
          CreateDirectory(""T"") 'Method Call 2            
          NormalMethod() ' Method Call 1
          NormalMethod() ' Method Call 2
       End Sub

       Sub NormalMethod()
       End Sub
 End Module
            ");

            ProjectId  prj1Id = ProjectId.CreateNewId();
            DocumentId docId  = DocumentId.CreateNewId(prj1Id);

            Solution sln = new AdhocWorkspace().CurrentSolution
                           .AddProject(prj1Id, "testDeclareReferences", "testAssembly", LanguageNames.VisualBasic)
                           .AddMetadataReference(prj1Id, MscorlibRef)
                           .AddDocument(docId, "testFile", tree.GetText());

            Project prj = sln.GetProject(prj1Id).WithCompilationOptions(new VisualBasic.VisualBasicCompilationOptions(OutputKind.ConsoleApplication, embedVbCoreRuntime: true));

            tree = await prj.GetDocument(docId).GetSyntaxTreeAsync();

            Compilation comp = await prj.GetCompilationAsync();

            SemanticModel semanticModel = comp.GetSemanticModel(tree);

            SyntaxNode declareMethod = tree.GetRoot().DescendantNodes().OfType <Microsoft.CodeAnalysis.VisualBasic.Syntax.DeclareStatementSyntax>().FirstOrDefault();
            SyntaxNode normalMethod  = tree.GetRoot().DescendantNodes().OfType <Microsoft.CodeAnalysis.VisualBasic.Syntax.MethodStatementSyntax>().ToList()[1];

            // declared method calls
            var symbol     = semanticModel.GetDeclaredSymbol(declareMethod);
            var references = await SymbolFinder.FindReferencesAsync(symbol, prj.Solution);

            Assert.Equal(expected: 2, actual: references.ElementAt(0).Locations.Count());

            // normal method calls
            symbol     = semanticModel.GetDeclaredSymbol(normalMethod);
            references = await SymbolFinder.FindReferencesAsync(symbol, prj.Solution);

            Assert.Equal(expected: 2, actual: references.ElementAt(0).Locations.Count());
        }
Example #49
0
        public async Task PinvokeMethodReferences_CS()
        {
            var tree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(
                @"

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Runtime.InteropServices;
static class Module1
{
	[DllImport(""kernel32"", EntryPoint = ""CreateDirectoryA"", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
    public static extern int CreateDirectory(string lpPathName);

        private static int prop;
        public static int Prop1
        {
            get { return prop; }
            set
            {
                CreateDirectory(""T"");
                // Method Call 1
                prop = value;
                prop = null;
            }
        }

        public static void Main()
        {
            CreateDirectory(""T""); // Method Call 2            
            NormalMethod(); // Method Call 1
            NormalMethod(); // Method Call 2
        }

        public static void NormalMethod()
        {
        }
    }
                ");

            ProjectId  prj1Id = ProjectId.CreateNewId();
            DocumentId docId  = DocumentId.CreateNewId(prj1Id);

            var sln = new AdhocWorkspace().CurrentSolution
                      .AddProject(prj1Id, "testDeclareReferences", "testAssembly", LanguageNames.CSharp)
                      .AddMetadataReference(prj1Id, MscorlibRef)
                      .AddDocument(docId, "testFile", tree.GetText());

            Project prj = sln.GetProject(prj1Id).WithCompilationOptions(new CSharp.CSharpCompilationOptions(OutputKind.ConsoleApplication));

            tree = await prj.GetDocument(docId).GetSyntaxTreeAsync();

            Compilation comp = await prj.GetCompilationAsync();

            SemanticModel semanticModel = comp.GetSemanticModel(tree);

            List <Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax> methodlist = tree.GetRoot().DescendantNodes().OfType <Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax>().ToList();
            SyntaxNode declareMethod = methodlist.ElementAt(0);
            SyntaxNode normalMethod  = methodlist.ElementAt(2);

            // pinvoke method calls
            var symbol     = semanticModel.GetDeclaredSymbol(declareMethod);
            var references = await SymbolFinder.FindReferencesAsync(symbol, prj.Solution);

            Assert.Equal(2, references.ElementAt(0).Locations.Count());

            // normal method calls
            symbol     = semanticModel.GetDeclaredSymbol(normalMethod);
            references = await SymbolFinder.FindReferencesAsync(symbol, prj.Solution);

            Assert.Equal(2, references.ElementAt(0).Locations.Count());
        }
 /// <summary>
 /// Adds the generated files to a specific project but does not include the subversion files.
 /// </summary>
 /// <param name="project">Project to add the generated files to</param>
 /// <param name="directory">Directory that contains the generated files</param>
 private static void addGeneratedFiles(Project project, string directory)
 {
     addFilesToProject(project, directory,
                       /* don't include .svn files */ d => d == ".svn",
                       /* and don't include "hash" dirs */ f => f.ToLower() == "hash");
 }
        private async Task <List <Report> > GetProjectReports()
        {
            _reports = new List <Report>();

            if (Project != null)
            {
                var settingsBundle       = Project.GetSettings();
                var reportViewerSettings = settingsBundle.GetSettingsGroup <ReportsViewerSettings>();
                var savedReports         = DeserializeReports(reportViewerSettings.ReportsJson.Value);
                var studioReports        = GetStudioReports();
                var reports = new List <Report>();

                // get the reports managed by studio with updated settings from the reviewer
                foreach (var studioReport in studioReports)
                {
                    var savedReport = savedReports.FirstOrDefault(a => a.Id == studioReport.Id);
                    var report      = new Report
                    {
                        Id             = studioReport.Id,
                        Name           = studioReport.Name,
                        Description    = studioReport.Description,
                        Date           = studioReport.Date,
                        Group          = savedReport?.Group ?? studioReport.Group,
                        Language       = studioReport.Language,
                        Path           = studioReport.Path,
                        TemplateId     = studioReport.TemplateId,
                        IsCustomReport = studioReport.IsCustomReport,
                        IsStudioReport = true,
                        IsSelected     = savedReport?.IsSelected ?? false,
                        XsltPath       = savedReport?.XsltPath ?? string.Empty
                    };

                    if (!TaskTemplateIdProvider.TaskTemplateIdExists(studioReport.TemplateId))
                    {
                        TaskTemplateIdProvider.AddTemplateId(studioReport.TemplateId, studioReport.TemplateId);
                    }

                    reports.Add(report);
                }

                // recover also the saved reports that aren't managed by Studio
                foreach (var report in savedReports)
                {
                    var existingReport = reports.FirstOrDefault(a => a.Id == report.Id);
                    if (existingReport == null)
                    {
                        reports.Add(report);
                    }
                }

                var customReportTemplates = DeserializeCustomReportTemplates(reportViewerSettings.CustomReportTemplatesJson.Value);
                var overwrite             = UICultureChanged(reportViewerSettings);

                var reportTemplates = GetCustomReportTemplates();
                var updatedReports  = GetUpdatedReports(reports, reportTemplates, overwrite, ref customReportTemplates);
                UpdateCustomTemplateReports(customReportTemplates);

                _reports = updatedReports;
            }

            return(await Task.FromResult(GetClonedReports(_reports)));
        }
        /// <summary>
        /// Builds the pipeline.
        /// </summary>
        /// <param name="config">The config.</param>
        /// <param name="reportProgress">The report progress.</param>
        private void buildPipeline(PipelineConfiguration config,
                                   /* curr -> total -> unit */ Action <int, int> reportProgress)
        {
            var sourceAssemblyPath = config.SourceProject.GetOutputAssembly();

            if (!File.Exists(sourceAssemblyPath))
            {
                throw new InvalidOperationException("Please build the contract project before attempting to generate a pipeline.");
            }

            List <PipelineSegmentSource> sources = buildSource(sourceAssemblyPath);

            Project hostAddInView = null,
                    hostSideAdapterProject = null,
                    addInSideAdapterProject = null,
                    addInView = null, view = null;

            var sourceProject = config.SourceProject;
            var destPath = config.ProjectDestination;
            var outputPath = config.BuildDestination;

            int progress = 0;

            reportProgress(progress, sources.Count);

            foreach (var pipelineSegmentSource in sources)
            {
                // Create add-in project
                Project project = createAddInProject(destPath, pipelineSegmentSource, config);

                // if this returns null, then we have cancelled from the createAddInProject.
                // also create new add in project.
                if (project == null)
                {
                    return;
                }

                // Set output path
                setOutputPath(project, pipelineSegmentSource.Type, outputPath);

                switch (pipelineSegmentSource.Type)
                {
                case SegmentType.HostAddInView:
                    hostAddInView = project;
                    break;

                case SegmentType.HostSideAdapter:
                    hostSideAdapterProject = project;
                    break;

                case SegmentType.AddInSideAdapter:
                    addInSideAdapterProject = project;
                    break;

                case SegmentType.AddInView:
                    addInView = project;
                    break;

                case SegmentType.View:
                    view = project;
                    break;
                }

                reportProgress(progress++, sources.Count);
            }

            assertAdaptersNotNull(hostSideAdapterProject, addInSideAdapterProject);

            var hostSideAdapter2  = (VSProject2)hostSideAdapterProject.Object;
            var addInSideAdapter2 = (VSProject2)addInSideAdapterProject.Object;

            // why copy the reference twice?
            addContractReference(hostSideAdapter2, sourceProject);
            addContractReference(addInSideAdapter2, sourceProject);

            if (view == null) // both add-in-side adapters and host-side adapters.
            {
                addProjectReference(hostSideAdapter2, hostAddInView);
                addProjectReference(addInSideAdapter2, addInView);
            }
            else
            {
                addProjectReference(hostSideAdapter2, view);
                addProjectReference(addInSideAdapter2, view);
            }

            reportProgress(1, 1);
            var dte2 = (DTE2)sourceProject.DTE;

            foreach (UIHierarchyItem solution in dte2.ToolWindows.SolutionExplorer.UIHierarchyItems)
            {
                collapseFolder(hostSideAdapter2, addInSideAdapter2, solution);
            }
        }
        /// <summary>
        /// This function generated the project corresponding to the passed pipelineComponent.
        /// </summary>
        /// <param name="destPath">The destination path of the projects.</param>
        /// <param name="pipelineComponent">Which component to generate the project for.</param>
        /// <returns>The project generated.</returns>
        private Project createAddInProject(string destPath, PipelineSegmentSource pipelineComponent, PipelineConfiguration config)
        {
            // dest path will be the root of the project where we have addins,
            // so we need to select the correct project for this specific segment, if there is
            // one and take its path, otherwise do destPath.Combine(pipelineComponent.Name);
            string name;

            destPath = destPath.Combine(getSubPath(config, pipelineComponent, destPath, out name));
            var generatedDestPath = destPath.Combine(GENERETED_FILES_DIRECTORY);

            // the getSubPath will use the configuration to get the correct project,
            // if one was selected, and otherwise will return the name of the pipeline segment
            // so that getProjByName will return null if it's not existing and otherwise the correct
            // and selected project.
            Project proj = getProjByName(name);

            if (proj == null)
            {
                if (Directory.Exists(destPath))
                {
                    if (DialogResult.Yes == MessageBox.Show(string.Format("The directory {0} already exists, " +
                                                                          " would you like to delete it and use it for the generated files for the segment named {1}?",
                                                                          destPath, name), "Already existing directory", MessageBoxButtons.YesNoCancel))
                    {
                        Directory.Delete(destPath, true);
                    }
                    else
                    {
                        return(null);
                    }
                }

                Directory.CreateDirectory(destPath);

                string connectPath = Path.GetDirectoryName(typeof(PipelineBuilderCommand).Assembly.Location);

                proj = dte.Solution.AddFromTemplate(connectPath.Combine("Template.csproj"),
                                                    destPath,
                                                    pipelineComponent.Name + ".csproj",
                                                    false);
            }

            if (proj == null)
            {
                throw new InvalidOperationException("Problem in adding from template. "
                                                    + "You installation files for the pipeline builder may be corrupted.");
            }

            if (Directory.Exists(generatedDestPath))
            {
                CheckSumValidator.ValidateCheckSum(generatedDestPath);
            }

            deleteGeneratedFiles(proj);
            assertHasDirectory(proj, generatedDestPath);
            generateSourceFiles(pipelineComponent, generatedDestPath);
            addGeneratedFiles(proj, generatedDestPath);

            CheckSumValidator.StoreCheckSum(generatedDestPath);

            return(proj);
        }
Example #54
0
        /// <summary>
        /// Recursive Function to walk a specified directory tree and add the files into a Visual Studio C project.
        /// </summary>
        /// <param name="proj">Destination Project</param>
        /// <param name="sourceDir">Source Directory to begin walking</param>
        /// <param name="destinationDir">Destination Directory of new project to copy files to</param>
        /// <param name="filter">VCFilter object to add files to</param>
        /// <returns></returns>
        public bool WalkDirectoryTree(Project proj, DirectoryInfo sourceDir, DirectoryInfo destinationDir, VCFilter filter)
        {
            VCFilter localFilter = filter;

            System.IO.FileInfo[]      files   = null;
            System.IO.DirectoryInfo[] subDirs = null;

            // First, process all the files directly under this folder
            try
            {
                files = sourceDir.GetFiles("*.*");

                foreach (FileInfo file in files)
                {
                    if (file.Name.Contains("vcxproj"))
                    {
                        AddSummaryString("Selected project already converted.");
                        return(false);
                    }
                }
            }
            catch (UnauthorizedAccessException e)
            {
                return(false);
            }

            if (files != null)
            {
                // Now find all the subdirectories under this directory.
                subDirs = sourceDir.GetDirectories();

                if (localFilter == null)
                {
                    foreach (System.IO.DirectoryInfo dirInfo in subDirs)
                    {
                        if (dirInfo.Name == "src")
                        {
                            IVCCollection tmpCollection;
                            VCFilter      tmpFilter;
                            tmpCollection = (proj.Object as VCProject).Filters;
                            tmpFilter     = tmpCollection.Item("Source Files");
                            (proj.Object as VCProject).RemoveFilter(tmpFilter);
                        }
                        if (dirInfo.Name == "res")
                        {
                            IVCCollection tmpCollection;
                            VCFilter      tmpFilter;
                            tmpCollection = (proj.Object as VCProject).Filters;
                            tmpFilter     = tmpCollection.Item("Resource Files");
                            (proj.Object as VCProject).RemoveFilter(tmpFilter);
                        }
                    }
                }

                foreach (System.IO.FileInfo fi in files)
                {
                    AddFileToProject(proj, fi.FullName, destinationDir.FullName, localFilter);
                }

                foreach (System.IO.DirectoryInfo dirInfo in subDirs)
                {
                    VCFilter newFilter = AddFolderToProject(proj, destinationDir.FullName, dirInfo.Name, localFilter);
                    // Resursive call for each subdirectory.
                    DirectoryInfo source      = new DirectoryInfo(dirInfo.FullName);
                    DirectoryInfo destination = new DirectoryInfo(Path.Combine(destinationDir.FullName, dirInfo.Name));
                    if (!WalkDirectoryTree(proj, source, destination, newFilter))
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
        private static void AddPackage(ReferenceSwitcherConfiguration configuration, ProjectInSolution solutionProject, Project project, string packageName, string packageVersion)
        {
            var projectName =
                Path.GetFileNameWithoutExtension(solutionProject.AbsolutePath);

            var switchedProject = (
                from r in configuration.Restore
                where string.Equals(r.Name, projectName, StringComparison.OrdinalIgnoreCase)
                select r).FirstOrDefault();

            if (switchedProject != null)
            {
                var reference = switchedProject.GetSwitchedPackage(packageName);

                if (!string.IsNullOrEmpty(reference.Include))
                {
                    project.AddItem("Reference", reference.Include, reference.Metadata);
                }
                else
                {
                    if (!project.Items.Any(i => i.ItemType == "PackageReference" && i.EvaluatedInclude == packageName)) // check that the reference is not already present
                    {
                        var items = project.AddItem("PackageReference", packageName,
                                                    new[] { new KeyValuePair <string, string>("Version", packageVersion) });

                        items.ToList().ForEach(item =>
                        {
                            item.Metadata?.ToList().ForEach(metadata =>
                                                            metadata.Xml.ExpressedAsAttribute = true);
                        });
                    }
                }
            }
        }
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            DTE              dte        = Package.GetGlobalService(typeof(SDTE)) as DTE;
            Solution2        currSol2   = (EnvDTE80.Solution2)dte.Solution;
            CommandUtilities util       = new CommandUtilities(this.ServiceProvider);
            ProjectItem      currItem   = null;
            ProjectItem      configItem = null;
            String           configName = "Innovator.config";

            if (dte.ActiveDocument == null)
            {
                util.showError("No active window.", "Active Window Required");
                return;
            }

            Project currProj = dte.ActiveDocument.ProjectItem.ContainingProject;

            if (string.IsNullOrEmpty(currProj.FullName))
            {
                util.showError("Method must be in a project.", "Project Required");
                return;
            }

            try {
                configItem = currProj.ProjectItems.Item(configName);
            }
            catch (ArgumentException) {
                util.showError("Required Innovator.config file not found in selected project.", "Config File Not Found");
                return;
            }

            string      configPath = configItem.FileNames[0];
            XmlDocument configXML  = new XmlDocument();

            configXML.Load(configPath);

            Dictionary <string, string> configDic = util.ReadConfigFile(configXML);
            string val = "";

            if (configDic.TryGetValue("failCheck", out val))
            {
                return;
            }

            string csTemplateName;

            configDic.TryGetValue("csTemplateName", out csTemplateName);
            string jsTemplateName;

            configDic.TryGetValue("jsTemplateName", out jsTemplateName);
            string methodInsertTag;

            configDic.TryGetValue("methodInsertTag", out methodInsertTag);
            string methodEndTag;

            configDic.TryGetValue("methodEndTag", out methodEndTag);
            string serverName;

            configDic.TryGetValue("serverName", out serverName);
            string databaseName;

            configDic.TryGetValue("databaseName", out databaseName);
            string loginName;

            configDic.TryGetValue("loginName", out loginName);
            string loginPassword;

            configDic.TryGetValue("loginPassword", out loginPassword);
            string defaultMethodSearch;

            configDic.TryGetValue("defaultMethodSearch", out defaultMethodSearch);

            string fileName   = dte.ActiveDocument.Name;
            string methodName = fileName.Substring(0, fileName.LastIndexOf('.'));

            try {
                currItem = dte.ActiveDocument.ProjectItem;
            }
            catch (ArgumentException) {
                util.showError("Method file not found in current project.", "Method File Not Found");
                return;
            }

            string filePath      = currItem.FileNames[0];
            string templateLines = File.ReadAllText(filePath);
            int    insertIndex   = templateLines.IndexOf(methodInsertTag) + methodInsertTag.Length;
            int    endIndex      = templateLines.IndexOf(methodEndTag);

            //Connect to Aras Server
            HttpServerConnection connection;

            Aras.IOM.Innovator inn;

            connection = IomFactory.CreateHttpServerConnection(serverName, databaseName, loginName, loginPassword);
            Aras.IOM.Item iLogin = connection.Login();
            if (iLogin.isError())
            {
                util.showError("Unable to connect to Aras Innovator with the server, database, and login information provided in Innovator.config of the active project.", "Connection Error");
                return;
            }

            inn = new Aras.IOM.Innovator(connection);

            Item iQry = inn.newItem();

            iQry.loadAML(string.Format(@"<Item type='Method' action='lock' where=""[Method].name='{0}' and [Method].is_current='1'""  doGetItem='0'/>", methodName));
            iQry = iQry.apply();

            connection.Logout();

            if (iQry.isError())
            {
                util.showError(iQry.getErrorString(), "Error");
                return;
            }

            //string methodCode = iQry.getProperty("method_code");

            //string modifiedLines = templateLines.Substring(0, insertIndex) + "\n" + methodCode + "\n" + templateLines.Substring(endIndex);

            //File.WriteAllText(filePath, modifiedLines);

            util.setStatusBar(string.Format("Success: {0} was succesfully locked on the server with method ", methodName));
        }
Example #57
0
        private void ShowMenu(Project project, List <TimelineEvent> plays, EventType eventType, Time time,
                              List <EventType> eventTypes, bool editableName)
        {
            bool isLineup = false, isSubstitution = false;

            this.plays     = plays;
            this.eventType = eventType;
            this.time      = time;
            this.project   = project;

            if (eventType != null)
            {
                string label = String.Format("{0} in {1}", Catalog.GetString("Add new event"), eventType.Name);
                newPlay.SetLabel(label);
                newPlay.Visible = true;
            }
            else
            {
                newPlay.Visible = false;
            }

            if (plays == null)
            {
                plays = new List <TimelineEvent> ();
            }
            else if (plays.Count == 1)
            {
                isLineup       = plays [0] is LineupEvent;
                isSubstitution = plays [0] is SubstitutionEvent;
            }

            if (isLineup || isSubstitution)
            {
                edit.Visible       = true;
                del.Visible        = isSubstitution;
                snapshot.Visible   = moveCat.Visible = drawings.Visible =
                    addPLN.Visible = render.Visible = duplicate.Visible = false;
            }
            else
            {
                edit.Visible      = editableName && plays.Count == 1;
                snapshot.Visible  = plays.Count == 1;
                moveCat.Visible   = plays.Count == 1 && eventTypes != null;
                drawings.Visible  = plays.Count == 1 && plays [0].Drawings.Count > 0;
                del.Visible       = plays.Count > 0;
                addPLN.Visible    = plays.Count > 0;
                render.Visible    = plays.Count > 0;
                duplicate.Visible = plays.Count > 0;
            }

            if (plays.Count > 0)
            {
                string label = String.Format("{0} ({1})", Catalog.GetString("Delete"), plays.Count);
                del.SetLabel(label);
                label = String.Format("{0} ({1})", Catalog.GetString("Add to playlist"), plays.Count);
                addPLN.SetLabel(label);
                label = String.Format("{0} ({1})", Catalog.GetString("Export to video file"), plays.Count);
                render.SetLabel(label);
                label = String.Format("{0} ({1})", Catalog.GetString("Duplicate "), plays.Count);
                duplicate.SetLabel(label);
            }

            if (moveCat.Visible)
            {
                Menu catMenu = new Menu();
                foreach (EventType c in eventTypes)
                {
                    if (plays [0].EventType == c)
                    {
                        continue;
                    }
                    var item = new MenuItem(c.Name);
                    catMenu.Append(item);
                    item.Activated += (sender, e) => {
                        Config.EventsBroker.EmitMoveToEventType(plays [0], c);
                    };
                }
                catMenu.ShowAll();
                moveCat.Submenu = catMenu;
            }

            if (drawings.Visible)
            {
                Menu drawingsMenu = new Menu();
                for (int i = 0; i < plays [0].Drawings.Count; i++)
                {
                    int      index       = i;
                    MenuItem drawingItem = new MenuItem(Catalog.GetString("Drawing ") + (i + 1));
                    MenuItem editItem    = new MenuItem(Catalog.GetString("Edit"));
                    MenuItem deleteItem  = new MenuItem(Catalog.GetString("Delete"));
                    Menu     drawingMenu = new Menu();

                    drawingsMenu.Append(drawingItem);
                    drawingMenu.Append(editItem);
                    drawingMenu.Append(deleteItem);
                    editItem.Activated += (sender, e) => {
                        Config.EventsBroker.EmitDrawFrame(plays [0], index,
                                                          plays [0].Drawings [index].CameraConfig, false);
                    };
                    deleteItem.Activated += (sender, e) => {
                        plays [0].Drawings.RemoveAt(index);
                        plays [0].UpdateMiniature();
                    };
                    drawingItem.Submenu = drawingMenu;
                    drawingMenu.ShowAll();
                }
                drawingsMenu.ShowAll();
                drawings.Submenu = drawingsMenu;
            }

            if (project.Playlists != null)
            {
                Menu     plMenu = new Menu();
                MenuItem item;

                foreach (Playlist pl in project.Playlists)
                {
                    item = new MenuItem(pl.Name);
                    plMenu.Append(item);
                    item.Activated += (sender, e) => {
                        IEnumerable <IPlaylistElement> elements;

                        elements = plays.Select(p => new PlaylistPlayElement(p, project.Description.FileSet));
                        Config.EventsBroker.EmitAddPlaylistElement(pl, elements.ToList());
                    };
                }

                item = new MenuItem(Catalog.GetString("Create new playlist..."));
                plMenu.Append(item);
                item.Activated += (sender, e) => {
                    IEnumerable <IPlaylistElement> elements;
                    elements = plays.Select(p => new PlaylistPlayElement(p, project.Description.FileSet));
                    Config.EventsBroker.EmitAddPlaylistElement(null, elements.ToList());
                };

                plMenu.ShowAll();
                addPLN.Submenu = plMenu;
            }

            Popup();
        }
Example #58
0
 public void ShowTimelineMenu(Project project, List <TimelineEvent> plays, EventType eventType, Time time)
 {
     ShowMenu(project, plays, eventType, time, null, false);
 }
        static void Build(string distrUrl, string netVersion, string networkExistCondition)
        {
            var appDir  = AppUtils.AppDir();
            var appName = "Убийца нежелательных окон 1С";

            var releaseDir = $@"{appDir}\..\..\..\bin\x86\Release";

            if (Directory.Exists(releaseDir))
            {
                Directory.Delete(releaseDir, true);
            }

            string solutionUrl      = $@"{appDir}\..\..\..\KillerOfUnwantedWindows1C.sln";
            string projectUrl       = $@"{appDir}\..\..\..\KillerOfUnwantedWindows1C.csproj";
            string projectBackupUrl = Path.ChangeExtension(projectUrl, ".bak");

            if (System.IO.File.Exists(projectBackupUrl))
            {
                System.IO.File.Copy(projectBackupUrl, projectUrl, true);
                System.IO.File.Delete(projectBackupUrl);
            }

            System.IO.File.Copy(projectUrl, projectBackupUrl);
            var projectFileText    = System.IO.File.ReadAllText(projectUrl);
            var newProjectFileText = projectFileText.Replace("<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>",
                                                             $"<TargetFrameworkVersion>v{netVersion}</TargetFrameworkVersion>");

            System.IO.File.WriteAllText(projectUrl, newProjectFileText);

            Process.Start(@"c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe",
                          $"/build Release {solutionUrl}").WaitForExit();

            System.IO.File.Copy(projectBackupUrl, projectUrl, true);
            System.IO.File.Delete(projectBackupUrl);

            Process.Start(@"x:\Utils\sign_sha1_sha256.cmd", $@"{appDir}\..\..\..\bin\x86\Release\KillerOfUnwantedWindows1C.exe").WaitForExit();

            var project = new Project(
                appName,
                new LaunchCondition(networkExistCondition, $"Пожалуйста, установите .NET Framework {netVersion} или выберите другой установщик программы для уже установленной у вас версии .NET Framework."),
                new Dir(
                    @"%ProgramFiles%\Killer of unwanted windows 1C",
                    new WixSharp.File($@"{appDir}\..\..\..\bin\x86\Release\config.xml"),
                    new WixSharp.File(
                        $@"{appDir}\..\..\..\bin\x86\Release\KillerOfUnwantedWindows1C.exe",
                        new FileShortcut(appName, @"%Startup%")
            {
                Arguments = "-r"
            }
                        ),
                    new WixSharp.File($@"{appDir}\..\..\..\LICENSE"),
                    new WixSharp.File($@"{appDir}\..\..\..\readme.txt")
                    ),
                new Property("ALLUSERS", "1"),
                new RegValueProperty("NET2", Microsoft.Win32.RegistryHive.LocalMachine,
                                     @"Software\Microsoft\NET Framework Setup\NDP\v2.0.50727", "Install", "0"),
                new RegValueProperty("NET4A", Microsoft.Win32.RegistryHive.LocalMachine,
                                     @"Software\Microsoft\NET Framework Setup\NDP\v4.0\Client", "Install", "0"),
                new RegValueProperty("NET4B", Microsoft.Win32.RegistryHive.LocalMachine,
                                     @"Software\Microsoft\NET Framework Setup\NDP\v4\Client", "Install", "0")
                );

            project.GUID = new Guid("6f330b47-2577-43ad-9095-1861ba25889b");
            project.ControlPanelInfo.Manufacturer = "Vladimir Milkin (helpme1c.ru)";
            project.ControlPanelInfo.HelpLink     = "https://helpme1c.ru";
            project.ControlPanelInfo.ProductIcon  = $@"{appDir}\..\..\..\images\killer.ico";
            project.UI = WUI.WixUI_InstallDir;
            project.PreserveTempFiles = true;
            project.PreserveDbgFiles  = true;
            project.MajorUpgrade      = new MajorUpgrade()
            {
                AllowDowngrades          = true,
                AllowSameVersionUpgrades = false
            };
            project.Language = "ru-RU";

            var partsOfVersion = netVersion.Split(new char[] { '.' });
            int major          = int.Parse(partsOfVersion[0] + partsOfVersion[1]);
            int minor          = partsOfVersion.Length > 2 ? int.Parse(partsOfVersion[2]) : 0;

            var appVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

            project.Version          = new Version(major, minor, appVersion.Build, appVersion.Revision);
            project.LicenceFile      = $@"{appDir}\..\..\..\LICENSE.rtf";
            project.RebootSupressing = RebootSupressing.ReallySuppress;

            var msiUrl = $@"{distrUrl}\setup_for_net_{netVersion.Replace(".", "_")}.msi";

            Compiler.BuildMsi(project, msiUrl);

            Process.Start(@"x:\Utils\sign_sha1.cmd", msiUrl).WaitForExit();
        }
        public void AddAttachments(
            Project dbtask, 
            List<HttpPostedFileBase> uploadedAttachments, 
            HttpServerUtility server)
        {
            if (uploadedAttachments == null)
            {
                return;
            }

            if (!Directory.Exists(server.MapPath(TasksConstants.MainContentFolder)))
            {
                Directory.CreateDirectory(server.MapPath(TasksConstants.MainContentFolder));
            }

            if (!Directory.Exists(server.MapPath(TasksConstants.MainContentFolder + "\\" + dbtask.Id)))
            {
                Directory.CreateDirectory(server.MapPath(TasksConstants.MainContentFolder + "\\" + dbtask.Id));
            }

            foreach (var file in uploadedAttachments)
            {
                var filename = Path.GetFileName(file.FileName);
                file.SaveAs(server.MapPath(TasksConstants.MainContentFolder + "\\" + dbtask.Id + "\\" + filename));
                dbtask.Attachments.Add(new Attachment() { Name = file.FileName });

                this.Update(dbtask);
            }
        }