public static IEnumerable<DiagnosticMessage> Diagnose(
            ProjectContext context,
            IEnumerable<string> currentSearchPaths)
        {
            var result = new List<DiagnosticMessage>();
            var project = context.ProjectFile;
            var libraries = context.LibraryManager.GetLibraries();

            var updatedSearchPath = GetUpdatedSearchPaths(currentSearchPaths, project.ResolveSearchPaths());
            var projectCandiates = GetProjectCandidates(updatedSearchPath);
            var rootDependencies = libraries.FirstOrDefault(library => string.Equals(library.Identity.Name, project.Name))
                                           ?.Dependencies
                                           ?.ToDictionary(libraryRange => libraryRange.Name);

            foreach (var library in libraries)
            {
                var diagnostic = Validate(library, projectCandiates, rootDependencies);
                if (diagnostic != null)
                {
                    result.Add(diagnostic);
                }
            }

            return result;
        }
Beispiel #2
0
        // Constructor. Will connect to Project Online with mandratory credentials.
        public UserProps(string site, string username, string password)
        {
            try
            {
                if (site == "" || username == "" || password == "")
                {
                    throw (new Exception("Must supply site, username and password!"));
                }

                Console.WriteLine("Connecting to Project Online @ " + site + "...");

                var securePassword = new SecureString();
                foreach (var ch in password.ToCharArray())
                {
                    securePassword.AppendChar(ch);
                }

                context = new ProjectContext(site);
                context.Credentials = new SharePointOnlineCredentials(username, securePassword);
                context.Load(context.Web);
                context.ExecuteQuery();
                Console.WriteLine("   Connected to '" + context.Web.Title + "'");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }
 public void SetUp()
 {
     _context = new ProjectContext();
     _context.Hierarchy = DataMother.GrammarProject().LoadTests();
     _context.Library = DataMother.GrammarsProjectRunner().GetLibary();
     _service = new UsageService(_context);
 }
        public void ConstructorWithParameters()
        {
            var compilation = CSharpCompilation.Create("nothing");
            var projectContext = new ProjectContext();
            var resourceDescriptorList = new List<ResourceDescriptor>();
            var diagnosticList = new List<Diagnostic>();
            var metadataReferenceList = new List<IMetadataReference>();
            var target = new BeforeCompileContext(
                compilation,
                projectContext,
                () =>
                {
                    return resourceDescriptorList;
                },
                () =>
                {
                    return diagnosticList;
                },
                () =>
                {
                   return metadataReferenceList;
                });

            Assert.Equal(compilation, target.Compilation);
            Assert.Equal(projectContext, target.ProjectContext);
            Assert.Equal(resourceDescriptorList, target.Resources);
            Assert.Equal(diagnosticList, target.Diagnostics);
            Assert.Equal(metadataReferenceList, target.MetadataReferences);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            using (var projectContext = new ProjectContext())
            {
                using (var unitOfWork = new UnitOfWork(projectContext))
                {
                    IdentityUser user = await unitOfWork.Users.FindUser(context.UserName, context.Password);

                    if (user == null)
                    {
                        context.SetError("invalid_grant", "The user name or password is incorrect.");
                        return;
                    }
                }
            }


            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);

        }
Beispiel #6
0
 public FileProviderImpl(ProjectContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     _context = context;
 }
Beispiel #7
0
        private ProjectId AddProject(ProjectContext project)
        {
            // Create the framework specific project and add it to the workspace
            var projectInfo = ProjectInfo.Create(
                                ProjectId.CreateNewId(),
                                VersionStamp.Create(),
                                project.ProjectFile.Name + "+" + project.TargetFramework,
                                project.ProjectFile.Name,
                                LanguageNames.CSharp,
                                project.ProjectFile.ProjectFilePath);

            OnProjectAdded(projectInfo);

            // TODO: ctor argument?
            var configuration = "Debug";

            var compilationOptions = project.GetLanguageSpecificCompilerOptions(project.TargetFramework, configuration);

            var compilationSettings = ToCompilationSettings(compilationOptions, project.TargetFramework, project.ProjectFile.ProjectDirectory);

            OnParseOptionsChanged(projectInfo.Id, new CSharpParseOptions(compilationSettings.LanguageVersion, preprocessorSymbols: compilationSettings.Defines));

            OnCompilationOptionsChanged(projectInfo.Id, compilationSettings.CompilationOptions);

            foreach (var file in project.ProjectFile.Files.SourceFiles)
            {
                AddSourceFile(projectInfo, file);
            }

            var exporter = project.CreateExporter(configuration);

            foreach (var dependency in exporter.GetDependencies())
            {
                var projectDependency = dependency.Library as ProjectDescription;
                if (projectDependency != null)
                {
                    var projectDependencyContext = ProjectContext.Create(projectDependency.Project.ProjectFilePath, projectDependency.Framework);

                    var id = AddProject(projectDependencyContext);

                    OnProjectReferenceAdded(projectInfo.Id, new ProjectReference(id));
                }
                else
                {
                    foreach (var asset in dependency.CompilationAssemblies)
                    {
                        OnMetadataReferenceAdded(projectInfo.Id, GetMetadataReference(asset.ResolvedPath));
                    }
                }

                foreach (var file in dependency.SourceReferences)
                {
                    AddSourceFile(projectInfo, file);
                }
            }

            return projectInfo.Id;
        }
Beispiel #8
0
 public UnitOfWork(ProjectContext context)
 {
     _context = context;
     Products = new ProductRepository(_context);
     Categories = new CategoryRepository(_context);
     Users = new AuthRepository(_context);
     Carts = new CartRepository(_context);
     Orders = new OrderRepository(_context);
 }
Beispiel #9
0
        public static ProjectContextSnapshot Create(ProjectContext context, string configuration, IEnumerable<string> currentSearchPaths)
        {
            var snapshot = new ProjectContextSnapshot();

            var allDependencyDiagnostics = new List<DiagnosticMessage>();
            allDependencyDiagnostics.AddRange(context.LibraryManager.GetAllDiagnostics());
            allDependencyDiagnostics.AddRange(DependencyTypeChangeFinder.Diagnose(context, currentSearchPaths));

            var diagnosticsLookup = allDependencyDiagnostics.ToLookup(d => d.Source);

            var allExports = context.CreateExporter(configuration)
                                    .GetAllExports()
                                    .ToDictionary(export => export.Library.Identity.Name);

            var allSourceFiles = new List<string>(context.ProjectFile.Files.SourceFiles);
            var allFileReferences = new List<string>();
            var allProjectReferences = new List<ProjectReferenceDescription>();
            var allDependencies = new Dictionary<string, DependencyDescription>();

            // All exports are returned. When the same library name have a ReferenceAssembly type export and a Package type export
            // both will be listed as dependencies. Prefix "fx/" will be added to ReferenceAssembly type dependency.
            foreach (var export in allExports.Values)
            {
                allSourceFiles.AddRange(export.SourceReferences.Select(f => f.ResolvedPath));
                var diagnostics = diagnosticsLookup[export.Library].ToList();
                var description = DependencyDescription.Create(export.Library, diagnostics, allExports);
                allDependencies[description.Name] = description;

                var projectDescription = export.Library as ProjectDescription;
                if (projectDescription != null)
                {
                    if (projectDescription.Identity.Name != context.ProjectFile.Name)
                    { 
                        allProjectReferences.Add(ProjectReferenceDescription.Create(projectDescription));
                    }
                }
                else
                {
                    allFileReferences.AddRange(export.CompilationAssemblies.Select(asset => asset.ResolvedPath));
                }
            }

            snapshot.RootDependency = context.ProjectFile.Name;
            snapshot.TargetFramework = context.TargetFramework;
            snapshot.SourceFiles = allSourceFiles.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(path => path).ToList();
            snapshot.CompilerOptions = context.GetLanguageSpecificCompilerOptions(context.TargetFramework, configuration);
            snapshot.ProjectReferences = allProjectReferences.OrderBy(reference => reference.Name).ToList();
            snapshot.FileReferences = allFileReferences.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(path => path).ToList();
            snapshot.DependencyDiagnostics = allDependencyDiagnostics;
            snapshot.Dependencies = allDependencies;

            return snapshot;
        }
Beispiel #10
0
        public void DefaultConstructorSetAllPropertiesNull()
        {
            var target = new ProjectContext();

            // nothing is set
            Assert.Null(target.Configuration);
            Assert.Null(target.Name);
            Assert.Null(target.ProjectDirectory);
            Assert.Null(target.ProjectFilePath);
            Assert.Null(target.TargetFramework);
            Assert.Null(target.Version);
        }
        private static IEnumerable<string> GetSourceFiles(ProjectContext context, string configuration)
        {
            var compilerOptions = context.ProjectFile.GetCompilerOptions(context.TargetFramework, configuration);

            if (compilerOptions.CompileInclude == null)
            {
                return context.ProjectFile.Files.SourceFiles;
            }

            var includeFiles = IncludeFilesResolver.GetIncludeFiles(compilerOptions.CompileInclude, "/", diagnostics: null);

            return includeFiles.Select(f => f.SourcePath);
        }
        public static ProjectContextSnapshot Create(ProjectContext context, string configuration, IEnumerable<string> currentSearchPaths)
        {
            var snapshot = new ProjectContextSnapshot();
            
            var allDependencyDiagnostics = new List<DiagnosticMessage>();
            allDependencyDiagnostics.AddRange(context.LibraryManager.GetAllDiagnostics());
            allDependencyDiagnostics.AddRange(DependencyTypeChangeFinder.Diagnose(context, currentSearchPaths));

            var diagnosticsLookup = allDependencyDiagnostics.ToLookup(d => d.Source);

            var allSourceFiles = new List<string>(context.ProjectFile.Files.SourceFiles);
            var allFileReferences = new List<string>();
            var allProjectReferences = new List<ProjectReferenceDescription>();
            var allDependencies = new Dictionary<string, DependencyDescription>();
            
            foreach (var export in context.CreateExporter(configuration).GetDependencies())
            {
                allSourceFiles.AddRange(export.SourceReferences);
                allFileReferences.AddRange(export.CompilationAssemblies.Select(asset => asset.ResolvedPath));

                var library = export.Library;
                var diagnostics = diagnosticsLookup[library].ToList();
                var description = DependencyDescription.Create(library, diagnostics);
                allDependencies[description.Name] = description;

                var projectDescription = library as ProjectDescription;

                if (projectDescription != null)
                {
                    allProjectReferences.Add(ProjectReferenceDescription.Create(projectDescription));
                }
            }

            snapshot.RootDependency = context.ProjectFile.Name;
            snapshot.TargetFramework = context.TargetFramework;
            snapshot.SourceFiles = allSourceFiles.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(path => path).ToList();
            snapshot.CompilerOptions = context.ProjectFile.GetCompilerOptions(context.TargetFramework, configuration);
            snapshot.ProjectReferences = allProjectReferences.OrderBy(reference => reference.Name).ToList();
            snapshot.FileReferences = allFileReferences.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(path => path).ToList();
            snapshot.DependencyDiagnostics = allDependencyDiagnostics;
            snapshot.Dependencies = allDependencies;

            return snapshot;
        }
Beispiel #13
0
 public BaseService()
 {
     db = new ProjectContext();
 }
 private bool IsPrecompiledContext(ProjectContext context)
 {
     return(context == null || !IsDynamicContext(context));
 }
 public EFCreatePublisher(ProjectContext context, FluentCreatePublisherValidator validator, IMapper mapper)
 {
     _context   = context;
     _validator = validator;
     _mapper    = mapper;
 }
 public LoginController(ProjectContext context)
 {
     dbContext = context;
 }
Beispiel #17
0
 public ProjectRepository(IUnitOfWork<ProjectContext> uow)
 {
     _context = uow.Context;
     this._dbSet = _context.Set<Project>();
     _uow = uow;
 }
Beispiel #18
0
        private static bool CompileNative(
            ProjectContext context,
            string configuration,
            string outputOptionValue,
            bool buildProjectReferences,
            string intermediateOutputValue,
            string archValue,
            string ilcArgsValue,
            string ilcPathValue,
            bool isCppMode)
        {
            var outputPath             = GetOutputPath(context, configuration, outputOptionValue);
            var nativeOutputPath       = Path.Combine(GetOutputPath(context, configuration, outputOptionValue), "native");
            var intermediateOutputPath =
                GetIntermediateOutputPath(context, configuration, intermediateOutputValue, outputOptionValue);

            Directory.CreateDirectory(nativeOutputPath);
            Directory.CreateDirectory(intermediateOutputPath);

            var compilationOptions = context.ProjectFile.GetCompilerOptions(context.TargetFramework, configuration);
            var managedOutput      =
                GetProjectOutput(context.ProjectFile, context.TargetFramework, configuration, outputPath);

            var nativeArgs = new List <string>();

            // Input Assembly
            nativeArgs.Add($"{managedOutput}");

            // ILC Args
            if (!string.IsNullOrWhiteSpace(ilcArgsValue))
            {
                nativeArgs.Add("--ilcargs");
                nativeArgs.Add($"{ilcArgsValue}");
            }

            // ILC Path
            if (!string.IsNullOrWhiteSpace(ilcPathValue))
            {
                nativeArgs.Add("--ilcpath");
                nativeArgs.Add(ilcPathValue);
            }

            // CodeGen Mode
            if (isCppMode)
            {
                nativeArgs.Add("--mode");
                nativeArgs.Add("cpp");
            }

            // Configuration
            if (configuration != null)
            {
                nativeArgs.Add("--configuration");
                nativeArgs.Add(configuration);
            }

            // Architecture
            if (archValue != null)
            {
                nativeArgs.Add("--arch");
                nativeArgs.Add(archValue);
            }

            // Intermediate Path
            nativeArgs.Add("--temp-output");
            nativeArgs.Add($"{intermediateOutputPath}");

            // Output Path
            nativeArgs.Add("--output");
            nativeArgs.Add($"{nativeOutputPath}");

            // Write Response File
            var rsp = Path.Combine(intermediateOutputPath, $"dotnet-compile-native.{context.ProjectFile.Name}.rsp");

            File.WriteAllLines(rsp, nativeArgs);

            // TODO Add -r assembly.dll for all Nuget References
            //     Need CoreRT Framework published to nuget

            // Do Native Compilation
            var result = Command.Create("dotnet-compile-native", $"--rsp \"{rsp}\"")
                         .ForwardStdErr()
                         .ForwardStdOut()
                         .Execute();

            return(result.ExitCode == 0);
        }
Beispiel #19
0
        private static bool CompileProject(ProjectContext context, string configuration, string outputPath, string intermediateOutputPath, List <LibraryExport> dependencies)
        {
            Reporter.Output.WriteLine($"Compiling {context.RootProject.Identity.Name.Yellow()} for {context.TargetFramework.DotNetFrameworkName.Yellow()}");
            var sw = Stopwatch.StartNew();

            var diagnostics = new List <DiagnosticMessage>();
            var missingFrameworkDiagnostics = new List <DiagnosticMessage>();

            // Collect dependency diagnostics
            foreach (var diag in context.LibraryManager.GetAllDiagnostics())
            {
                if (diag.ErrorCode == ErrorCodes.DOTNET1011 ||
                    diag.ErrorCode == ErrorCodes.DOTNET1012)
                {
                    missingFrameworkDiagnostics.Add(diag);
                }

                diagnostics.Add(diag);
            }

            if (missingFrameworkDiagnostics.Count > 0)
            {
                // The framework isn't installed so we should short circuit the rest of the compilation
                // so we don't get flooded with errors
                PrintSummary(missingFrameworkDiagnostics, sw);
                return(false);
            }

            // Dump dependency data
            ShowDependencyInfo(dependencies);

            // Get compilation options
            var outputName = GetProjectOutput(context.ProjectFile, context.TargetFramework, configuration, outputPath);

            // Assemble args
            var compilerArgs = new List <string>()
            {
                $"--temp-output:{intermediateOutputPath}",
                $"--out:{outputName}"
            };

            var compilationOptions = context.ProjectFile.GetCompilerOptions(context.TargetFramework, configuration);

            if (!string.IsNullOrEmpty(compilationOptions.KeyFile))
            {
                // Resolve full path to key file
                compilationOptions.KeyFile = Path.GetFullPath(Path.Combine(context.ProjectFile.ProjectDirectory, compilationOptions.KeyFile));
            }

            // Add compilation options to the args
            compilerArgs.AddRange(compilationOptions.SerializeToArgs());

            foreach (var dependency in dependencies)
            {
                var projectDependency = dependency.Library as ProjectDescription;

                if (projectDependency != null)
                {
                    if (projectDependency.Project.Files.SourceFiles.Any())
                    {
                        var projectOutputPath = GetProjectOutput(projectDependency.Project, projectDependency.Framework, configuration, outputPath);
                        compilerArgs.Add($"--reference:{projectOutputPath}");
                    }
                }
                else
                {
                    compilerArgs.AddRange(dependency.CompilationAssemblies.Select(r => $"--reference:{r.ResolvedPath}"));
                }
                compilerArgs.AddRange(dependency.SourceReferences);
            }

            if (!AddResources(context.ProjectFile, compilerArgs, intermediateOutputPath))
            {
                return(false);
            }

            // Add project source files
            var sourceFiles = context.ProjectFile.Files.SourceFiles;

            compilerArgs.AddRange(sourceFiles);

            var compilerName = context.ProjectFile.CompilerName;

            compilerName = compilerName ?? "csc";

            // Write RSP file
            var rsp = Path.Combine(intermediateOutputPath, $"dotnet-compile.{context.ProjectFile.Name}.rsp");

            File.WriteAllLines(rsp, compilerArgs);

            // Run pre-compile event
            var contextVariables = new Dictionary <string, string>()
            {
                { "compile:TargetFramework", context.TargetFramework.DotNetFrameworkName },
                { "compile:Configuration", configuration },
                { "compile:OutputFile", outputName },
                { "compile:OutputDir", outputPath },
                { "compile:ResponseFile", rsp }
            };

            RunScripts(context, ScriptNames.PreCompile, contextVariables);

            var result = Command.Create($"dotnet-compile-{compilerName}", $"@\"{rsp}\"")
                         .OnErrorLine(line =>
            {
                var diagnostic = ParseDiagnostic(context.ProjectDirectory, line);
                if (diagnostic != null)
                {
                    diagnostics.Add(diagnostic);
                }
                else
                {
                    Reporter.Error.WriteLine(line);
                }
            })
                         .OnOutputLine(line =>
            {
                var diagnostic = ParseDiagnostic(context.ProjectDirectory, line);
                if (diagnostic != null)
                {
                    diagnostics.Add(diagnostic);
                }
                else
                {
                    Reporter.Output.WriteLine(line);
                }
            }).Execute();

            // Run post-compile event
            contextVariables["compile:CompilerExitCode"] = result.ExitCode.ToString();
            RunScripts(context, ScriptNames.PostCompile, contextVariables);

            var success = result.ExitCode == 0;

            if (success && compilationOptions.EmitEntryPoint.GetValueOrDefault())
            {
                var runtimeContext = ProjectContext.Create(context.ProjectDirectory, context.TargetFramework, new[] { RuntimeIdentifier.Current });
                MakeRunnable(runtimeContext,
                             outputPath,
                             runtimeContext.CreateExporter(configuration));
            }

            return(PrintSummary(diagnostics, sw, success));
        }
Beispiel #20
0
 public DependencyRepository()
 {
     _dbContext = new ProjectContext();
 }
Beispiel #21
0
 private readonly ProjectContext _context; public DemoRepository(ProjectContext context) : base(context)
 {
     _context = context;
 }
Beispiel #22
0
 public AdvertRepository(ProjectContext context) : base(context)
 {
 }
 public OrderService(ProjectContext context) : base(context)
 {
 }
Beispiel #24
0
 //used in incremental precondition checks
 public static IEnumerable <string> GetCommandsInvokedByCompile(ProjectContext project)
 {
     return(new List <string> {
         ResolveCompilerName(project), "compile"
     });
 }
Beispiel #25
0
 // used in incremental compilation
 public static IEnumerable <string> GetCompilationSources(ProjectContext project) => project.ProjectFile.Files.SourceFiles;
Beispiel #26
0
 public UserDAO()
 {
     _context = new ProjectContext();
 }
Beispiel #27
0
 public TenderFilesController(ProjectContext context)
 {
     _context = context;
 }
Beispiel #28
0
        public static int Main(string[] args)
        {
            DebugHelper.HandleDebugSwitch(ref args);

            var app = new CommandLineApplication();

            app.Name        = "dotnet compile";
            app.FullName    = ".NET Compiler";
            app.Description = "Compiler for the .NET Platform";
            app.HelpOption("-h|--help");

            var output                = app.Option("-o|--output <OUTPUT_DIR>", "Directory in which to place outputs", CommandOptionType.SingleValue);
            var intermediateOutput    = app.Option("-t|--temp-output <OUTPUT_DIR>", "Directory in which to place temporary outputs", CommandOptionType.SingleValue);
            var framework             = app.Option("-f|--framework <FRAMEWORK>", "Compile a specific framework", CommandOptionType.MultipleValue);
            var configuration         = app.Option("-c|--configuration <CONFIGURATION>", "Configuration under which to build", CommandOptionType.SingleValue);
            var noProjectDependencies = app.Option("--no-project-dependencies", "Skips building project references.", CommandOptionType.NoValue);
            var project               = app.Argument("<PROJECT>", "The project to compile, defaults to the current directory. Can be a path to a project.json or a project directory");

            // Native Args
            var native  = app.Option("-n|--native", "Compiles source to native machine code.", CommandOptionType.NoValue);
            var arch    = app.Option("-a|--arch <ARCH>", "The architecture for which to compile. x64 only currently supported.", CommandOptionType.SingleValue);
            var ilcArgs = app.Option("--ilcargs <ARGS>", "Command line arguments to be passed directly to ILCompiler.", CommandOptionType.SingleValue);
            var ilcPath = app.Option("--ilcpath <PATH>", "Path to the folder containing custom built ILCompiler.", CommandOptionType.SingleValue);
            var cppMode = app.Option("--cpp", "Flag to do native compilation with C++ code generator.", CommandOptionType.NoValue);

            app.OnExecute(() =>
            {
                // Locate the project and get the name and full path
                var path = project.Value;
                if (string.IsNullOrEmpty(path))
                {
                    path = Directory.GetCurrentDirectory();
                }

                var buildProjectReferences = !noProjectDependencies.HasValue();
                var isNative          = native.HasValue();
                var isCppMode         = cppMode.HasValue();
                var archValue         = arch.Value();
                var ilcArgsValue      = ilcArgs.Value();
                var ilcPathValue      = ilcPath.Value();
                var configValue       = configuration.Value() ?? Constants.DefaultConfiguration;
                var outputValue       = output.Value();
                var intermediateValue = intermediateOutput.Value();

                // Load project contexts for each framework and compile them
                bool success = true;
                var contexts = framework.HasValue() ?
                               framework.Values.Select(f => ProjectContext.Create(path, NuGetFramework.Parse(f))) :
                               ProjectContext.CreateContextForEachFramework(path);
                foreach (var context in contexts)
                {
                    success &= Compile(context, configValue, outputValue, intermediateOutput.Value(), buildProjectReferences);
                    if (isNative && success)
                    {
                        success &= CompileNative(context, configValue, outputValue, buildProjectReferences, intermediateValue, archValue, ilcArgsValue, ilcPathValue, isCppMode);
                    }
                }

                return(success ? 0 : 1);
            });

            try
            {
                return(app.Execute(args));
            }
            catch (Exception ex)
            {
#if DEBUG
                Console.Error.WriteLine(ex);
#else
                Console.Error.WriteLine(ex.Message);
#endif
                return(1);
            }
        }
 public EfEmployee(ProjectContext context) : base(context)
 {
 }
Beispiel #30
0
        private static void CopyContents(ProjectContext context, string outputPath)
        {
            var sourceFiles = context.ProjectFile.Files.GetCopyToOutputFiles();

            Copy(sourceFiles, context.ProjectDirectory, outputPath);
        }
Beispiel #31
0
 public ValidationsController()
 {
     projectContext = new ProjectContext();
 }
 public void Setup()
 {
     Palaso.Reporting.ErrorReport.IsOkToInteractWithUser = false;
     _folder      = new TemporaryFolder("BookCollectionTests");
     _fileLocator = new BloomFileLocator(new CollectionSettings(), new XMatterPackFinder(new string[] {}), ProjectContext.GetFactoryFileLocations(), ProjectContext.GetFoundFileLocations());
     _collection  = new BookCollection(_folder.Path, BookCollection.CollectionType.TheOneEditableCollection, new BookSelection());
 }
Beispiel #33
0
 public UserRepository(ProjectContext db)
 {
     this._db = db;
 }
Beispiel #34
0
 public AuthRepository(ProjectContext context)
 {
     _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(context));
     _roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
 }
Beispiel #35
0
 public UpdateCustomerCardCommandHandler(ProjectContext context)
 {
     _context = context;
 }
Beispiel #36
0
        private void HandleCurrentProjectChanged(object sender, CurrentProjectChangedEventArgs e)
        {
            projectContext = e.NewProject;

            OnCanExecuteChanged();
        }
 public ProjectContext Init()
 {
     return dbContext ?? (dbContext = new ProjectContext());
 }
 private void ConnectToPWA()
 {
     projContext = ClaimClientContext.GetAuthenticatedContext<ProjectContext>(txtPWASite.Text);
 }
        internal void LoadProject(ProjectContext context)
        {
            var outputPaths        = context.GetOutputPaths(Configuration);
            var assemblyPath       = outputPaths.CompilationFiles.Assembly;
            var assemblyFolderPath = outputPaths.CompilationOutputPath;

            var libraryExporter = context.CreateExporter(Configuration);
            var runtimeIds      = GetRuntimeIdentifiers();

            foreach (var dependency in libraryExporter.GetAllExports())
            {
                var library = dependency.Library as ProjectDescription;
                var package = dependency.Library as PackageDescription;

                // Check for an unresolved library
                if (library != null && !library.Resolved)
                {
                    if (!IsAmbientAssembly(library.Identity.Name))
                    {
                        var assetFileName     = CompilerUtility.GetAssemblyFileName(library.Identity.Name);
                        var assetResolvedPath = ResolveAssemblyPath(assemblyFolderPath, assetFileName);

                        if (String.IsNullOrEmpty(assetResolvedPath))
                        {
                            // Fallback to this (possible) precompiled module bin folder
                            var path = Path.Combine(Paths.GetParentFolderPath(library.Path), Constants.BinDirectoryName, assetFileName);
                            assetResolvedPath = File.Exists(path) ? path : null;
                        }

                        if (!String.IsNullOrEmpty(assetResolvedPath))
                        {
                            LoadFromAssemblyPath(assetResolvedPath);
                            PopulateBinaryFolder(assemblyFolderPath, assetResolvedPath);
                            PopulateProbingFolder(assetResolvedPath);

                            var resourceFileName   = library.Identity.Name + ".resources.dll";
                            var assemblyFolderName = Paths.GetFolderName(assemblyFolderPath);

                            var assetFolderPath = Paths.GetParentFolderPath(assetResolvedPath);
                            var assetFolderName = Paths.GetFolderName(assetFolderPath);

                            var resourceAssemblies = Directory.GetFiles(assetFolderPath, resourceFileName, SearchOption.AllDirectories)
                                                     .Union(Directory.GetFiles(assemblyFolderPath, resourceFileName, SearchOption.AllDirectories))
                                                     .Union(Directory.GetFiles(_probingFolderPath, resourceFileName, SearchOption.AllDirectories));

                            foreach (var asset in resourceAssemblies)
                            {
                                var locale = Paths.GetParentFolderName(asset)
                                             .Replace(assetFolderName, String.Empty)
                                             .Replace(assemblyFolderName, String.Empty)
                                             .Replace(_probingDirectoryName, String.Empty);

                                PopulateBinaryFolder(assemblyFolderPath, asset, locale);
                                PopulateProbingFolder(asset, locale);
                                PopulateRuntimeFolder(asset, locale);
                            }
                        }
                    }
                }
                // Check for an unresolved package
                else if (package != null && !package.Resolved)
                {
                    string fallbackBinPath = null;

                    foreach (var asset in package.RuntimeAssemblies)
                    {
                        var assetName = Path.GetFileNameWithoutExtension(asset.Path);

                        if (!IsAmbientAssembly(assetName))
                        {
                            var assetFileName     = Path.GetFileName(asset.Path);
                            var assetResolvedPath = ResolveAssemblyPath(assemblyFolderPath, assetFileName);

                            if (String.IsNullOrEmpty(assetResolvedPath))
                            {
                                if (fallbackBinPath == null)
                                {
                                    fallbackBinPath = String.Empty;

                                    // Fallback to a (possible) parent precompiled module bin folder
                                    var parentBinPaths = CompilerUtility.GetOtherParentProjectsLocations(context, package)
                                                         .Select(x => Path.Combine(x, Constants.BinDirectoryName));

                                    foreach (var binaryPath in parentBinPaths)
                                    {
                                        var path = Path.Combine(binaryPath, assetFileName);

                                        if (File.Exists(path))
                                        {
                                            assetResolvedPath = path;
                                            fallbackBinPath   = binaryPath;
                                            break;
                                        }
                                    }
                                }
                                else if (!String.IsNullOrEmpty(fallbackBinPath))
                                {
                                    var path = Path.Combine(fallbackBinPath, assetFileName);
                                    assetResolvedPath = File.Exists(path) ? path : null;
                                }
                            }

                            if (!String.IsNullOrEmpty(assetResolvedPath))
                            {
                                LoadFromAssemblyPath(assetResolvedPath);
                                PopulateBinaryFolder(assemblyFolderPath, assetResolvedPath);
                                PopulateProbingFolder(assetResolvedPath);
                            }
                        }
                    }

                    foreach (var asset in package.RuntimeTargets)
                    {
                        var assetName = Path.GetFileNameWithoutExtension(asset.Path);

                        if (!IsAmbientAssembly(assetName))
                        {
                            var assetFileName = Path.GetFileName(asset.Path);

                            var relativeFolderPath = !String.IsNullOrEmpty(asset.Runtime)
                                ? Paths.GetParentFolderPath(asset.Path) : String.Empty;

                            var assetResolvedPath = ResolveAssemblyPath(assemblyFolderPath, assetFileName, relativeFolderPath);

                            if (String.IsNullOrEmpty(assetResolvedPath) && !String.IsNullOrEmpty(fallbackBinPath))
                            {
                                var path = Path.Combine(fallbackBinPath, relativeFolderPath, assetFileName);
                                assetResolvedPath = File.Exists(path) ? path : null;
                            }

                            if (!String.IsNullOrEmpty(assetResolvedPath))
                            {
                                if (runtimeIds.Contains(asset.Runtime))
                                {
                                    LoadFromAssemblyPath(assetResolvedPath);
                                }

                                PopulateBinaryFolder(assemblyFolderPath, assetResolvedPath, relativeFolderPath);
                                PopulateProbingFolder(assetResolvedPath, relativeFolderPath);
                            }
                        }
                    }

                    var runtimeAssets = new HashSet <string>(package.RuntimeAssemblies.Select(x => x.Path), StringComparer.OrdinalIgnoreCase);

                    foreach (var asset in package.CompileTimeAssemblies)
                    {
                        var assetFileName = Path.GetFileName(asset.Path);

                        if (!IsAmbientAssembly(assetFileName) && !runtimeAssets.Contains(asset.Path))
                        {
                            var assetResolvedPath = ResolveAssemblyPath(assemblyFolderPath, assetFileName, CompilerUtility.RefsDirectoryName);

                            if (String.IsNullOrEmpty(assetResolvedPath) && !String.IsNullOrEmpty(fallbackBinPath))
                            {
                                var path = Path.Combine(fallbackBinPath, CompilerUtility.RefsDirectoryName, assetFileName);
                                assetResolvedPath = File.Exists(path) ? path : null;
                            }

                            if (!String.IsNullOrEmpty(assetResolvedPath))
                            {
                                _compileOnlyAssemblies[assetFileName] = assetResolvedPath;
                                PopulateBinaryFolder(assemblyFolderPath, assetResolvedPath, CompilerUtility.RefsDirectoryName);
                                PopulateProbingFolder(assetResolvedPath, CompilerUtility.RefsDirectoryName);
                            }
                        }
                    }

                    if (!IsAmbientAssembly(package.Identity.Name))
                    {
                        foreach (var asset in package.ResourceAssemblies)
                        {
                            string locale;
                            if (asset.Properties.TryGetValue(CompilerUtility.LocaleLockFilePropertyName, out locale))
                            {
                                var assetFileName     = Path.GetFileName(asset.Path);
                                var assetResolvedPath = ResolveAssemblyPath(assemblyFolderPath, assetFileName, locale);

                                if (String.IsNullOrEmpty(assetResolvedPath) && !String.IsNullOrEmpty(fallbackBinPath))
                                {
                                    var path = Path.Combine(fallbackBinPath, locale, assetFileName);
                                    assetResolvedPath = File.Exists(path) ? path : null;
                                }

                                if (!String.IsNullOrEmpty(assetResolvedPath))
                                {
                                    PopulateBinaryFolder(assemblyFolderPath, assetResolvedPath, locale);
                                    PopulateProbingFolder(assetResolvedPath, locale);
                                    PopulateRuntimeFolder(assetResolvedPath, locale);
                                }
                            }
                        }
                    }
                }
                // Check for a precompiled library
                else if (library != null && !dependency.RuntimeAssemblyGroups.Any())
                {
                    if (!IsAmbientAssembly(library.Identity.Name))
                    {
                        var assetFileName     = CompilerUtility.GetAssemblyFileName(library.Identity.Name);
                        var assetResolvedPath = ResolveAssemblyPath(assemblyFolderPath, assetFileName);

                        if (String.IsNullOrEmpty(assetResolvedPath))
                        {
                            // Fallback to this precompiled project output path
                            var outputPath = CompilerUtility.GetAssemblyFolderPath(library.Project.ProjectDirectory,
                                                                                   Configuration, context.TargetFramework.DotNetFrameworkName);
                            var path = Path.Combine(outputPath, assetFileName);
                            assetResolvedPath = File.Exists(path) ? path : null;
                        }

                        if (!String.IsNullOrEmpty(assetResolvedPath))
                        {
                            LoadFromAssemblyPath(assetResolvedPath);
                            PopulateBinaryFolder(assemblyFolderPath, assetResolvedPath);
                            PopulateProbingFolder(assetResolvedPath);

                            var resourceFileName   = library.Identity.Name + ".resources.dll";
                            var assemblyFolderName = Paths.GetFolderName(assemblyFolderPath);

                            var assetFolderPath = Paths.GetParentFolderPath(assetResolvedPath);
                            var assetFolderName = Paths.GetFolderName(assetFolderPath);

                            var resourceAssemblies = Directory.GetFiles(assetFolderPath, resourceFileName, SearchOption.AllDirectories)
                                                     .Union(Directory.GetFiles(assemblyFolderPath, resourceFileName, SearchOption.AllDirectories))
                                                     .Union(Directory.GetFiles(_probingFolderPath, resourceFileName, SearchOption.AllDirectories));

                            foreach (var asset in resourceAssemblies)
                            {
                                var locale = Paths.GetParentFolderName(asset)
                                             .Replace(assetFolderName, String.Empty)
                                             .Replace(assemblyFolderName, String.Empty)
                                             .Replace(_probingDirectoryName, String.Empty);

                                PopulateBinaryFolder(assemblyFolderPath, asset, locale);
                                PopulateProbingFolder(asset, locale);
                                PopulateRuntimeFolder(asset, locale);
                            }
                        }
                    }
                }
                else
                {
                    foreach (var assetGroup in dependency.RuntimeAssemblyGroups)
                    {
                        foreach (var asset in assetGroup.Assets)
                        {
                            if (!IsAmbientAssembly(asset.Name))
                            {
                                if (runtimeIds.Contains(assetGroup.Runtime))
                                {
                                    LoadFromAssemblyPath(asset.ResolvedPath);
                                }

                                var relativeFolderPath = !String.IsNullOrEmpty(assetGroup.Runtime)
                                    ? Paths.GetParentFolderPath(asset.RelativePath) : String.Empty;

                                PopulateBinaryFolder(assemblyFolderPath, asset.ResolvedPath, relativeFolderPath);
                                PopulateProbingFolder(asset.ResolvedPath, relativeFolderPath);
                            }
                        }
                    }

                    var runtimeAssets = new HashSet <LibraryAsset>(dependency.RuntimeAssemblyGroups.GetDefaultAssets());

                    foreach (var asset in dependency.CompilationAssemblies)
                    {
                        if (!IsAmbientAssembly(asset.Name) && !runtimeAssets.Contains(asset))
                        {
                            _compileOnlyAssemblies[asset.Name] = asset.ResolvedPath;
                            PopulateBinaryFolder(assemblyFolderPath, asset.ResolvedPath, CompilerUtility.RefsDirectoryName);
                            PopulateProbingFolder(asset.ResolvedPath, CompilerUtility.RefsDirectoryName);
                        }
                    }

                    if (!IsAmbientAssembly(dependency.Library.Identity.Name))
                    {
                        foreach (var asset in dependency.ResourceAssemblies)
                        {
                            var assetResolvedPath = asset.Asset.ResolvedPath;

                            if (!String.IsNullOrEmpty(assetResolvedPath) && File.Exists(assetResolvedPath))
                            {
                                PopulateBinaryFolder(assemblyFolderPath, assetResolvedPath, asset.Locale);
                                PopulateProbingFolder(assetResolvedPath, asset.Locale);
                                PopulateRuntimeFolder(assetResolvedPath, asset.Locale);
                            }
                        }
                    }
                }
            }
        }
 public OutlineTreeService(ProjectContext context)
 {
     _context = context;
 }
        public void SetUp()
        {
            ProjectContext context = new ProjectContext();
            context.Hierarchy = DataMother.GrammarProject().LoadTests();
            context.Library = DataMother.GrammarsProjectRunner().GetLibary();
            UsageService service = new UsageService(context);

            container = new Container(x =>
            {
                x.For<IFixtureNodeView>().Use<StubFixtureNodeView>();
                x.For<IScreen<IFixtureNode>>().Use<FixtureNodePresenter>();
                x.For<UsageService>().Use(service);
            });

            factory = new ScreenFactory(container);

            fixture = context.Library.FixtureFor("Composite");

            subject = new FixtureNodeSubject(fixture);

            thePresenter = subject.CreateScreen(factory).ShouldBeOfType<FixtureNodePresenter>();
            thePresenter.Activate(null);
        }
Beispiel #42
0
 public RepositoryBase(IContextFactory _contextFactory)
 {
     _context = _contextFactory.GetContext();
     dbSet    = _context.Set <TEntity>();
 }
Beispiel #43
0
 public SyllabusController(ProjectContext context)
 {
     _context = context;
 }
Beispiel #44
0
        private void LoginProjectServer()
        {
            Log.WriteVerbose(new SourceInfo(), "Logging into project server on url:{0}", TB_Url.Text);
            ProjContext = new ProjectContext(TB_Url.Text);
            Log.WriteVerbose(new SourceInfo(), "Authenticating against {0} pwa instance", CB_Online.Checked ? "Online" : "OnPerm");

            if (CB_Online.Checked && RB_Forms.Checked)
            {
                //case online with user credential
                SecureString secpassword = new SecureString();
                foreach (char c in TB_Password.Text) secpassword.AppendChar(c);
                ProjContext.Credentials = new SharePointOnlineCredentials(TB_UserName.Text, secpassword);
            }
            else if (!CB_Online.Checked && RB_Forms.Checked)
            {
                //case onprem with user credential
                ProjContext.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
                FormsAuthenticationLoginInfo formsAuthInfo = new FormsAuthenticationLoginInfo(TB_UserName.Text, TB_Password.Text);
                ProjContext.FormsAuthenticationLoginInfo = formsAuthInfo;
            }
            else
            {
                //Default case - Windows Auth
                ProjContext.Credentials = CredentialCache.DefaultCredentials;
            }
            CsomHelper.ProjContext = ProjContext;
            CsomBase.CurrentResource = CsomHelper.LoadMe();
            CsomBase.CurrentUser = CsomBase.CurrentResource.User;
            if (_bge.TaskCancelled || _bge.ActionTask.IsFaulted)
            {
                return;
            }
            Log.WriteVerbose(new SourceInfo(), "Login on url:{0} for user:{1}", TB_Url.Text, CsomBase.CurrentUser.Title);
            DialogResult = DialogResult.OK;
        }
 public ProjectService(ProjectContext context)
 {
     _context = context;
 }
Beispiel #46
0
 public ProjectQueries(ProjectContext dbContext)//string connectString,
 {
     //_connectionString = connectString;
     _dbContext = dbContext;
 }
Beispiel #47
0
 public ProjectRepository(ProjectContext dbContext)
 {
     _dbContext = dbContext;
 }
        public ActionResult RunReport(int id_project, int id_user, string date)
        {
            using (var stream = new MemoryStream())
            {
                ApplicationContext db         = new ApplicationContext();
                ProjectContext     db2        = new ProjectContext();
                object             locked     = new object();
                const int          BufferSize = 8192;
                byte[]             buffer     = new byte[BufferSize];

                int                count            = db.SetResultModels.Where(u => u.ProjectID == id_project).Count();
                string             name_project     = db2.SetProjectModels.Where(u => u.Id == id_project).First().NameProject;
                Queue <InputModel> inputModelsQueue = new Queue <InputModel>();

                List <Models.Form.ResultModel> bd_tmp = db.SetResultModels.Where(u => u.ProjectID == id_project).ToList();

                if (id_user != 0)
                {
                    bd_tmp = bd_tmp.Where(u => u.UserID == id_user).ToList();
                }
                if (date != "null")
                {
                    DateTime StartDate = DateTime.Parse(date);
                    DateTime EndDate   = DateTime.Parse(date).AddDays(1);
                    bd_tmp = bd_tmp.Where(u => u.Data > StartDate && u.Data < EndDate).ToList();
                }
                int idi = 0;

                ////Создание списка файлов//
                bd_tmp.AsParallel().ForAll(u =>
                {
                    lock (locked)
                    {
                        if (System.IO.File.Exists(Path.Combine(Server.MapPath("~\\uploads"), u.BlankID.ToString() + "_" + name_project + ".mp3")))
                        {
                            inputModelsQueue.Enqueue(new InputModel {
                                Name = u.BlankID + "_" + name_project + ".mp3", Selected = true
                            });
                            System.Diagnostics.Debug.WriteLine("i === >>>>" + u.BlankID + "  state === >>>>" + true);
                            idi++;
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine("i === >>>>" + u.BlankID + "  state === >>>>" + false);
                        }
                    }
                });

                //Создание ZIP архива
                List <string> filenames = inputModelsQueue.Where(m => m.Selected == true).Select(f => f.Name).ToList();

                Session[name_project] = filenames;
                return(new JsonResult()
                {
                    Data = new
                    {
                        FileGuid = name_project,
                        MimeType = "application/zip",
                        FileName = name_project
                    }
                });
            }
        }
 public TodoItemsController(ProjectContext context)
 {
     _context = context;
 }
Beispiel #50
0
 public ProjectJsonWorkspace(ProjectContext context) : base(MefHostServices.DefaultHost, "Custom")
 {
     AddProject(context);
 }
Beispiel #51
0
 public FlowerController(ProjectContext context)
 {
     _context = context;
 }
Beispiel #52
0
        /// <summary>
        /// Handles the recursion through directories: if a folder looks like a Bloom book upload it; otherwise, try its children.
        /// Invisible folders like .hg are ignored.
        /// </summary>
        /// <param name="folder"></param>
        /// <param name="dlg"></param>
        /// <param name="container"></param>
        /// <param name="context"></param>
        private void UploadInternal(string folder, BulkUploadProgressDlg dlg, ApplicationContainer container, ref ProjectContext context)
        {
            if (Path.GetFileName(folder).StartsWith("."))
                return; // secret folder, probably .hg

            if (Directory.GetFiles(folder, "*.htm").Count() == 1)
            {
                // Exactly one htm file, assume this is a bloom book folder.
                dlg.Progress.WriteMessage("Starting to upload " + folder);

                // Make sure the files we want to upload are up to date.
                // Unfortunately this requires making a book object, which requires making a ProjectContext, which must be created with the
                // proper parent book collection if possible.
                var parent = Path.GetDirectoryName(folder);
                var collectionPath = Directory.GetFiles(parent, "*.bloomCollection").FirstOrDefault();
                if (collectionPath == null && context == null)
                {
                    collectionPath = Settings.Default.MruProjects.Latest;
                }
                if (context == null || context.SettingsPath != collectionPath)
                {
                    if (context != null)
                        context.Dispose();
                    // optimise: creating a context seems to be quite expensive. Probably the only thing we need to change is
                    // the collection. If we could update that in place...despite autofac being told it has lifetime scope...we would save some time.
                    // Note however that it's not good enough to just store it in the project context. The one that is actually in
                    // the autofac object (_scope in the ProjectContext) is used by autofac to create various objects, in particular, books.
                    context = container.CreateProjectContext(collectionPath);
                }
                var server = context.BookServer;
                var book = server.GetBookFromBookInfo(new BookInfo(folder, true));
                book.BringBookUpToDate(new NullProgress());

                // Assemble the various arguments needed to make the objects normally involved in an upload.
                // We leave some constructor arguments not actually needed for this purpose null.
                var bookSelection = new BookSelection();
                bookSelection.SelectBook(book);
                var currentEditableCollectionSelection = new CurrentEditableCollectionSelection();
                if (collectionPath != null)
                {
                    var collection = new BookCollection(collectionPath, BookCollection.CollectionType.SourceCollection,
                        bookSelection);
                    currentEditableCollectionSelection.SelectCollection(collection);
                }
                var publishModel = new PublishModel(bookSelection, new PdfMaker(), currentEditableCollectionSelection, null, server, _thumbnailer, null);
                publishModel.PageLayout = book.GetLayout();
                var view = new PublishView(publishModel, new SelectedTabChangedEvent(), new LocalizationChangedEvent(), this, null, null);
                string dummy;
                // Normally we let the user choose which languages to upload. Here, just the ones that have complete information.
                var langDict = book.AllLanguages;
                var languagesToUpload = langDict.Keys.Where(l => langDict[l]).ToArray();
                if (languagesToUpload.Any())
                    FullUpload(book, dlg.Progress, view, languagesToUpload, out dummy, dlg);
                return;
            }
            foreach (var sub in Directory.GetDirectories(folder))
                UploadInternal(sub, dlg, container, ref context);
        }
        // For applications that access both the Project Server CSOM and the SharePoint CSOM, you could
        // use the ProjectServer object. Those statements are commented out in this application.
        // However, it is not necessary to instantiate a ProjectServer object, because the the
        // ProjectContext object inherits from ClientContext in SharePoint.
        static void Main(string[] args)
        {
            projContext = new ProjectContext(pwaPath);
                //context = new ClientContext(pwaPath);
                //projSvr = new ProjectServer(context);
               // string userName = "******";
            //GUID for reshmee auckloo
            Guid resUID = new Guid("02C5EE34-5CE8-E411-80C1-00155D640C06");
            string customFieldName = "Staff Number";

            // Get the list of resources from Project Web App.
            projContext.Load(projContext.EnterpriseResources);
            projContext.Load(projContext.CustomFields);

            projContext.ExecuteQuery();

            Console.WriteLine("\nResource ID : Resource name ");

            int numResInCollection = projContext.EnterpriseResources.Count();
              var usrs = projContext.Web.SiteUsers;

            if (numResInCollection > 0)
            {
                projContext.Load(projContext.EnterpriseResources.GetByGuid(resUID));
                projContext.Load(projContext.EntityTypes.ResourceEntity);
                projContext.ExecuteQuery();

                var entRes2Edit = projContext.EnterpriseResources.GetByGuid(resUID);

                var userCustomFields = entRes2Edit.CustomFields;

                Guid ResourceEntityUID = projContext.EntityTypes.ResourceEntity.ID;

               var customfield = projContext.CustomFields.Where(x => x.Name == customFieldName);

               entRes2Edit[customfield.First().InternalName] = "3456";

                Console.WriteLine("\nEditing resource : GUID : Can Level");
                Console.WriteLine("\n{0} : {1} : {2}", entRes2Edit.Name, entRes2Edit.Id.ToString(),
                    entRes2Edit.CanLevel.ToString());

                // Toggle the CanLevel property.
                entRes2Edit.CanLevel = !entRes2Edit.CanLevel;

                // The entRes2Edit object is in the EnterpriseResources collection.
                projContext.EnterpriseResources.Update();

                // Save the change.
                projContext.ExecuteQuery();

                // Check that the change was made.
                projContext.Load(projContext.EnterpriseResources.GetByGuid(resUID));
                projContext.ExecuteQuery();

                entRes2Edit = projContext.EnterpriseResources.GetByGuid(resUID);

                Console.WriteLine("\n\nChanged resource : GUID : Can Level");
                Console.WriteLine("\n{0} : {1} : {2}", entRes2Edit.Name, entRes2Edit.Id.ToString(),
                    entRes2Edit.CanLevel.ToString());
            }

            Console.Write("\nPress any key to exit: ");
            Console.ReadKey(false);
        }