private bool ReplaceDll()
        {
            FileInfo dll = null;

            if (DotNetVersion.StartsWith("3.5"))
            {
                dll = Patcher.DLL35;
            }
            if (DotNetVersion.StartsWith("4.0"))
            {
                dll = Patcher.DLL40;
            }
            if (DotNetVersion.StartsWith("4.5"))
            {
                dll = Patcher.DLL45;
            }

            if (dll == null)
            {
                Console.WriteLine($"Warning: unknown version {DotNetVersion}");
                Console.WriteLine("Resuming with default (.Net 4.5) . Press Enter to confirm.");
                Console.ReadLine();
                dll = Patcher.DLL45;
            }

            var dllPath = Path.Combine(Bin.FullName, "ClientDependency.Core.dll");

            var backupDLL   = Path.Combine(Patcher.Backup_Folder, $"ClientDependency.Core-{Name.Replace("\\", "-")}.dll");
            var originalDLL = new FileInfo(dllPath).CopyTo(backupDLL, true);

            dll.CopyTo(dllPath, true);

            Console.WriteLine($"DLL version {DotNetVersion} replaced.");
            return(true);
        }
 public DependsOnIncompatibleFramework(Project project, Project dependsOnProject, DotNetVersion projectVersion, DotNetVersion dependsOnVersion)
 {
     Project          = project;
     DependsOnProject = dependsOnProject;
     ProjectVersion   = projectVersion;
     DependsOnVersion = dependsOnVersion;
 }
Example #3
0
        public void DotNetVersion_VersionSpsAndProfiles_Built()
        {
            // Fixture setup...
            var version      = new Version("4.0");
            var servicePacks = new[] {
                new Version("1.0"),
                new Version("2.0")
            };
            var profiles      = DotNetProfiles.Full;
            var dotNetVersion = new DotNetVersion(version);
            var builder       = new DotNetVersionBuilder
            {
                Version      = version,
                ServicePacks = servicePacks,
                Profiles     = profiles
            };

            // Exercise SUT...
            var builtVersion = builder.DotNetVersion;

            // Verify SUT...
            Assert.That(builtVersion.Version, Is.SameAs(version));
            Assert.That(builtVersion.ServicePacks, Is.SameAs(servicePacks));
            Assert.That(builtVersion.Profiles, Is.EqualTo(profiles));

            // Fixture teardown by GC...
        }
Example #4
0
        public void DotNetVersion_VersionAndProfiles_Built()
        {
            // Fixture setup...
            var version       = new Version("3.0");
            var profiles      = DotNetProfiles.Client;
            var dotNetVersion = new DotNetVersion(version);
            var builder       = new DotNetVersionBuilder
            {
                Version  = version,
                Profiles = profiles
            };

            // Exercise SUT...
            var builtVersion = builder.DotNetVersion;

            // Verify SUT...
            Assert.That(builtVersion.Version, Is.SameAs(version));
            Assert.That(
                builtVersion.ServicePacks,
                Is.EqualTo(dotNetVersion.ServicePacks)
                );
            Assert.That(builtVersion.Profiles, Is.EqualTo(profiles));

            // Fixture teardown by GC...
        }
Example #5
0
        /// <summary>
        /// Creates a per application user, sets security access rules for the application deployment directory
        /// and adds a new site to IIS without starting it
        /// </summary>
        /// <param name="appInfo">Structure that contains parameters required for deploying the application.</param>
        /// <param name="version">The dot net framework version supported by the application.</param>
        private void DeployApp(ApplicationInfo appInfo, DotNetVersion version)
        {
            this.startupLogger.Info(Strings.DeployingAppOnIis);

            string aspNetVersion = GetAspDotNetVersion(version);
            string password      = appInfo.WindowsPassword;
            string userName      = appInfo.WindowsUserName;

            try
            {
                mut.WaitOne();
                using (ServerManager serverMgr = new ServerManager())
                {
                    DirectoryInfo deploymentDir = new DirectoryInfo(appInfo.Path);

                    DirectorySecurity deploymentDirSecurity = deploymentDir.GetAccessControl();

                    deploymentDirSecurity.SetAccessRule(
                        new FileSystemAccessRule(
                            userName,
                            FileSystemRights.Write | FileSystemRights.Read | FileSystemRights.Delete | FileSystemRights.Modify,
                            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                            PropagationFlags.None,
                            AccessControlType.Allow));

                    deploymentDir.SetAccessControl(deploymentDirSecurity);

                    Site mySite = serverMgr.Sites.Add(this.appName, appInfo.Path, appInfo.Port);
                    mySite.ServerAutoStart = false;

                    ApplicationPool applicationPool = serverMgr.ApplicationPools[this.appName];
                    if (applicationPool == null)
                    {
                        serverMgr.ApplicationPools.Add(this.appName);
                        applicationPool = serverMgr.ApplicationPools[this.appName];
                        applicationPool.ManagedRuntimeVersion     = aspNetVersion;
                        applicationPool.ProcessModel.IdentityType = ProcessModelIdentityType.SpecificUser;
                        applicationPool.ProcessModel.UserName     = userName;
                        applicationPool.ProcessModel.Password     = password;
                        if (this.cpuTarget == CpuTarget.X86)
                        {
                            applicationPool.Enable32BitAppOnWin64 = true;
                        }
                        else
                        {
                            applicationPool.Enable32BitAppOnWin64 = false;
                        }
                    }

                    mySite.Applications["/"].ApplicationPoolName = this.appName;
                    FirewallTools.OpenPort(appInfo.Port, appInfo.Name);
                    serverMgr.CommitChanges();
                }
            }
            finally
            {
                mut.ReleaseMutex();
                this.startupLogger.Info(Strings.FinishedAppDeploymentOnIis);
            }
        }
Example #6
0
        /// <summary>
        /// sets the initial data for an application
        /// </summary>
        /// <param name="variables">All variables needed to run the application.</param>
        public void ConfigureApplication(ApplicationVariable[] variables)
        {
            try
            {
                ApplicationParsedData parsedData = PluginHelper.GetParsedData(variables);
                this.startupLogger = new FileLogger(parsedData.StartupLogFilePath);

                this.appName = RemoveSpecialCharacters(parsedData.AppInfo.Name) + parsedData.AppInfo.Port.ToString(CultureInfo.InvariantCulture);
                this.appPath = parsedData.AppInfo.Path;

                this.applicationInfo = parsedData.AppInfo;

                this.autoWireTemplates = parsedData.AutoWireTemplates;

                this.aspDotNetVersion = this.GetAppVersion(this.applicationInfo);

                this.AutowireApp(parsedData.AppInfo, variables, parsedData.GetServices(), parsedData.LogFilePath, parsedData.ErrorLogFilePath);

                this.cpuTarget = this.GetCpuTarget(this.applicationInfo);
            }
            catch (Exception ex)
            {
                this.startupLogger.Error(ex.ToString());
                throw;
            }
        }
Example #7
0
        private static void CopyPayloadExe(DotNetVersion version, string hostname)
        {
            byte[] svcexe = new byte[0];
            if (version == DotNetVersion.net35)
            {
                svcexe = Properties.Resources.test;
            }
            if (version == DotNetVersion.net40)
            {
                svcexe = Properties.Resources.test;
            }
            if (version == DotNetVersion.net45)
            {
                svcexe = Properties.Resources.test;
            }
            var path = hostname + @"\c$\windows\temp\test.exe";
            try
            {
                File.WriteAllBytes(path, svcexe);
#if DEBUG
                Console.WriteLine("[*] Copied {0} payload executable to {1}", version, hostname);
#endif
            }
            catch (UnauthorizedAccessException uae)
            {
                Console.WriteLine(uae.Message);
                return;
            }
        }
        public void ParseDotnetVersion(string text, DotNetType expectedType, string expectedVersion)
        {
            var version = DotNetVersion.TryParse(text);

            Assert.AreEqual(expectedType, version.DotNetType);
            Assert.AreEqual(expectedVersion, version.Version.ToString());
        }
Example #9
0
        //protected void Page_Load(object sender, EventArgs e)
        //{
        //    LoadInformation(GetSystemInfo());
        //    LoadInformation(GetSystemProcessorInfo());
        //    LoadInformation(GetSystemMemoryInfo());
        //    LoadInformation(GetSystemStorageInfo());
        //    LoadInformation(GetRequestHeaderInfo());
        //    LoadInformation(GetServerVariables());
        //    LoadInformation(GetEnvironmentVariables());
        //    LoadInformation(GetSessionInfo());
        //    LoadInformation(GetSystemObjectInfo());
        //    LoadInformation(GetMailObjectInfo());
        //    LoadInformation(GetUploadObjectInfo());
        //    LoadInformation(GetGraphicsObjectInfo());
        //    LoadInformation(GetOtherObjectInfo());
        //}
        private DataTable GetSystemInfo()
        {
            DataTable table = GenerateDataTable("System Information");

            //	Server Name
            Assign(table, "Server Name", HttpContext.Current.Server.MachineName);
            Assign(table, "Server IP", HttpContext.Current.Request.ServerVariables["LOCAl_ADDR"]);
            Assign(table, "Server Domain", HttpContext.Current.Request.ServerVariables["Server_Name"]);
            Assign(table, "Server Port", HttpContext.Current.Request.ServerVariables["Server_Port"]);
            //	Web Server
            Assign(table, "Web Server Version", HttpContext.Current.Request.ServerVariables["Server_SoftWare"]);
            //	Path
            Assign(table, "Virtual Request Path", HttpContext.Current.Request.FilePath);
            Assign(table, "Physical Request Path", HttpContext.Current.Request.PhysicalPath);
            Assign(table, "Virtual Application Root Path", HttpContext.Current.Request.ApplicationPath);
            Assign(table, "Physical Application Root Path", HttpContext.Current.Request.PhysicalApplicationPath);

            Assign(table, "Operating System", OperatingSystemOSVersion);
            Assign(table, "Operating System Installation Directory", Environment.SystemDirectory);
            Assign(table, ".Net Version", DotNetVersion.ToString());
            Assign(table, ".Net Language", DotNetLanguage);
            Assign(table, "Server Current Time", DateTime.Now.ToString());
            Assign(table, "System Uptime", SystemUptime.ToString());
            Assign(table, "Script Timeout", ScriptTimeout.ToString());
            return(table);
        }
Example #10
0
        /// <summary>
        /// Gets the dot net version that the application runs on.
        /// </summary>
        /// <param name="appInfo">The application info structure.</param>
        /// <returns>The .net version supported by the application</returns>
        private DotNetVersion GetAppVersion(ApplicationInfo appInfo)
        {
            this.startupLogger.Info(Strings.DeterminingApplication);

            string[] allAssemblies = Directory.GetFiles(appInfo.Path, "*.dll", SearchOption.AllDirectories);

            DotNetVersion version = DotNetVersion.Two;

            if (allAssemblies.Length == 0)
            {
                version = NetFrameworkVersion.GetFrameworkFromConfig(Path.Combine(appInfo.Path, "web.config"));
            }

            foreach (string assembly in allAssemblies)
            {
                if (NetFrameworkVersion.GetVersion(assembly) == DotNetVersion.Four)
                {
                    version = DotNetVersion.Four;
                    break;
                }
            }

            this.startupLogger.Info(Strings.DetectedNet + GetAspDotNetVersion(version));

            return(version);
        }
        public void ParseErrorMessage()
        {
            const string RequestedSdkVersion  = "6.0.301-rtm.22263.15";
            const string GlobalJsonFile       = "/Users/username/Source/format/global.json";
            const string ExpectedErrorMessage = $"Install the [{RequestedSdkVersion}] .NET SDK or update [{GlobalJsonFile}] to match an installed SDK.";

            var lines = new List <string>()
            {
                "The command could not be loaded, possibly because:",
                "  * You intended to execute a .NET application:",
                "      The application '--version' does not exist.",
                "  * You intended to execute a .NET SDK command:",
                "      A compatible .NET SDK was not found.",
                "",
                $"Requested SDK version: {RequestedSdkVersion}",
                $"global.json file: {GlobalJsonFile}",
                "",
                "Installed SDKs:",
                "6.0.105 [/usr/local/share/dotnet/sdk]",
                "6.0.202 [/usr/local/share/dotnet/sdk]",
                "6.0.300 [/usr/local/share/dotnet/sdk]",
                "7.0.100-preview.4.22252.9 [/usr/local/share/dotnet/sdk]",
                "",
                $"Install the [{RequestedSdkVersion}] .NET SDK or update [{GlobalJsonFile}] to match an installed SDK.",
                "",
                "Learn about SDK resolution:",
                "https://aka.ms/dotnet/sdk-not-found"
            };

            var cliVersion = DotNetVersion.Parse(lines);

            Assert.True(cliVersion.HasError);

            Assert.Equal(ExpectedErrorMessage, cliVersion.ErrorMessage);
        }
Example #12
0
        public DotNetVersionCheck GetVersion(DotNetVersion version)
        {
            switch (version)
            {
            case DotNetVersion.DotNet1:
                return(new Net1Check(this));

            case DotNetVersion.DotNet1_1:
                return(new Net1_1Check(this));

            case DotNetVersion.DotNet2:
                return(new Net2Check(this));

            case DotNetVersion.DotNet3:
                return(new Net3Check(this));

            case DotNetVersion.DotNet3_5:
                return(new Net3_5Check(this));

            case DotNetVersion.DotNet4:
                return(new Net4Check(this));

            case DotNetVersion.DotNet4_5:
                return(new Net4_5Check(this));

            default:
                return(new NullDotNetVersion(this));
            }
        }
Example #13
0
        private static void CopyServiceExe(DotNetVersion version, string hostname)
        {
            byte[] svcexe = new byte[0];
            if (version == DotNetVersion.net35)
            {
                svcexe = Properties.Resources.WindowsService1;
            }
            if (version == DotNetVersion.net40)
            {
                svcexe = Properties.Resources.WindowsService1;
            }
            if (version == DotNetVersion.net45)
            {
                svcexe = Properties.Resources.WindowsService1;
            }
            var path = hostname + @"\admin$\system32\csexecsvc.exe";
            try
            {
                File.WriteAllBytes(path, svcexe);
#if DEBUG
                Console.WriteLine("[*] Copied {0} service executable to {1}", version, hostname);
#endif
            }
            catch (UnauthorizedAccessException uae)
            {
                Console.WriteLine(uae.Message);
                return;
            }
        }
        private GruntTaskingMessage GetGruntTaskingMessage(GruntTasking tasking, DotNetVersion version)
        {
            string Message = "";

            switch (tasking.Type)
            {
            case GruntTaskingType.Assembly:
                switch (version)
                {
                case DotNetVersion.Net35:
                    Message = Convert.ToBase64String(this.GetCompressedILAssembly35(tasking.GruntTask.Name));
                    if (tasking.Parameters.Any())
                    {
                        Message += "," + String.Join(",", tasking.Parameters.Select(P => Convert.ToBase64String(Common.CovenantEncoding.GetBytes(P))));
                    }
                    break;

                case DotNetVersion.Net40:
                    Message = Convert.ToBase64String(this.GetCompressedILAssembly40(tasking.GruntTask.Name));
                    if (tasking.Parameters.Any())
                    {
                        Message += "," + String.Join(",", tasking.Parameters.Select(P => Convert.ToBase64String(Common.CovenantEncoding.GetBytes(P))));
                    }
                    break;
                }
                break;

            case GruntTaskingType.SetDelay:
                Message = tasking.Parameters[0];
                break;

            case GruntTaskingType.SetJitter:
                Message = tasking.Parameters[0];
                break;

            case GruntTaskingType.SetConnectAttempts:
                Message = tasking.Parameters[0];
                break;

            case GruntTaskingType.Connect:
                Message = tasking.Parameters[0] + "," + tasking.Parameters[1];
                break;

            case GruntTaskingType.Disconnect:
                Message = tasking.Parameters[0];
                break;

            default:
                Message = string.Join(",", tasking.Parameters.Select(P => Convert.ToBase64String(Common.CovenantEncoding.GetBytes(P))));
                break;
            }
            return(new GruntTaskingMessage
            {
                Type = tasking.Type,
                Name = tasking.Name,
                Message = Message,
                Token = tasking.GruntTask == null ? false : tasking.GruntTask.TokenTask
            });
        }
Example #15
0
        /// <exception cref="ArgumentNullException">
        /// <paramref name="project"/> is null.
        /// </exception>
        public Generator(Project project, SolutionType type, DotNetVersion dotNetVersion)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            solutionGenerator = CreateSolutionGenerator(project, type, dotNetVersion);
        }
Example #16
0
        static void InstallService(string hostname, DotNetVersion version)
        {

           while (true) {
                try
                {
                    using (var scmHandle = NativeMethods.OpenSCManager(hostname, null, NativeMethods.SCM_ACCESS.SC_MANAGER_CREATE_SERVICE))
                    {
                        if (scmHandle.IsInvalid)
                        {
                            throw new Win32Exception();
                        }

                        using (
                            var serviceHandle = NativeMethods.CreateService(
                                scmHandle,
                                GlobalVars.ServiceName,
                                GlobalVars.ServiceDisplayName,
                                NativeMethods.SERVICE_ACCESS.SERVICE_ALL_ACCESS,
                                NativeMethods.SERVICE_TYPES.SERVICE_WIN32_OWN_PROCESS,
                                NativeMethods.SERVICE_START_TYPES.SERVICE_AUTO_START,
                                NativeMethods.SERVICE_ERROR_CONTROL.SERVICE_ERROR_NORMAL,
                                GlobalVars.ServiceEXE,
                                null,
                                IntPtr.Zero,
                                null,
                                null,
                                null))
                        {
                            if (serviceHandle.IsInvalid)
                            {
                                throw new Win32Exception();
                            }
#if DEBUG
                            Console.WriteLine("[*] Installed {0} Service on {1}", version, hostname);
#endif
                            NativeMethods.StartService(serviceHandle, 0, null);
#if DEBUG
                            Console.WriteLine("[*] Service Started on {0}", hostname);
#endif
                            break;
                        }
                    }
                }//end of try
                catch (Exception e)
                {
                    Console.WriteLine("[*] InstallService Exception" + e.ToString());
                    Console.WriteLine("[*] Retry with cleanup ... ");
                    try
                    {
                        UninstallService(hostname);
                    }
                    catch (Exception) { }
                }
            }
        }
Example #17
0
        /// <summary>
        /// 檢查.netFramWork版本是否為4.0以上,不是則執行安裝程序
        /// </summary>
        private void CheckDotNetVersion()
        {
            float Version = DotNetVersion.GetVersion();

            if (Version >= 4.0f)
            {
                return;
            }

            InstallExe("dotNetFx40_Full_x86_x64.exe", true);
        }
Example #18
0
        public IEnumerable <Package> ExtractPackages(DotNetXMLDoc xmlDoc)
        {
            foreach (XmlNode packageNode in xmlDoc.SelectNodes("//package"))
            {
                string id            = packageNode.Attributes["id"].Value;
                string version       = packageNode.Attributes["version"].Value;
                string dotNetVersion = packageNode.Attributes["targetFramework"]?.Value;

                yield return(new Package(id, VersionWithSuffix.TryParse(version), DotNetVersion.TryParse(dotNetVersion)));
            }
        }
Example #19
0
        internal static string ToSerializedValue(this DotNetVersion value)
        {
            switch (value)
            {
            case DotNetVersion.Net35:
                return("Net35");

            case DotNetVersion.Net40:
                return("Net40");

            case DotNetVersion.NetCore31:
                return("NetCore31");
            }
            return(null);
        }
Example #20
0
        public void CtorWithoutProfileDefaultsToAllProfiles()
        {
            // Fixture setup...

            // Exercise SUT...
            var version = new DotNetVersion(new Version(), new Version[0]);

            // Verify SUT...
            Assert.That(
                version.Profiles,
                Is.EqualTo(DotNetProfiles.ClientFull)
                );

            // Fixture teardown by GC...
        }
Example #21
0
        public void CtorStoresArgs()
        {
            // Fixture setup...
            var version  = new Version();
            var packs    = new Version[0];
            var profiles = DotNetProfiles.Full;

            // Exercise and SUT...
            var netVersion = new DotNetVersion(version, packs, profiles);

            // Verify SUT...
            Assert.That(netVersion.Version, Is.EqualTo(version));
            Assert.That(netVersion.ServicePacks, Is.EqualTo(packs));
            Assert.That(netVersion.Profiles, Is.EqualTo(profiles));

            // Fixture teardown by GC...
        }
Example #22
0
        public void MaxDotNetVersion_OneVersion_ThatOne()
        {
            // Fixture setup...
            var version  = new DotNetVersion(new Version("1.0"));
            var detector = MockRepository.GenerateMock <IDetector>();

            detector.Expect(d => d.Versions).Return(new[] { version });
            Detector.Current = detector;

            // Exercise SUT...
            var maxDotNetVersion = Detector.MaxDotNetVersion;

            // Verify SUT...
            Assert.That(maxDotNetVersion, Is.EqualTo(version));

            // Fixture teardown...
            Detector.Current = null;
        }
        public void CanChangeVersionInPackagesConfig(string solutionPath, string projectName, string packageName, string dotNetVersion, string newVersion)
        {
            var solution = TestHelpers.GetSolution(solutionPath);
            var project  = solution.Projects.FirstOrDefault(p => p.Name == projectName);
            var modifier = DIRegistrar.GetInstance <NugetPackageModifier>();

            modifier.ChangeNugetPackageVersionInPackagesConfig(
                project,
                packageName,
                DotNetVersion.TryParse(dotNetVersion),
                VersionWithSuffix.TryParse(newVersion));

            var reader         = DIRegistrar.GetInstance <INugetReferenceReader>();
            var packagesConfig = reader.TryReadPackagesConfig(project.ProjectDirectory);
            var package        = packagesConfig.Packages.FirstOrDefault(p => p.ID == packageName);

            Assert.AreEqual(newVersion, package.Version.ToString());
        }
Example #24
0
 /// <summary>
 /// check/display the version of .NET installed on the machine
 /// </summary>
 void CheckDotNetVersion()
 {
     try
     {
         // check for the installed .NET versions
         logger.Log("The .NET Runtime = " + DotNetVersion.GetRuntimeVersionFromEnvironment());
         logger.Log(DotNetVersion.GetDotNetVerFromRegistry());
         if (DotNetVersion.GetDotNetVerFromRegistry() == "The .NET Framework 4.5 or later NOT detected")
         {
             logger.Log("Installed versions of the .NET Framework that are:\n");
             logger.Log(DotNetVersion.GetPreV45FromRegistry());
         }
     }
     catch (Exception ex)
     {
         logger.Log("Error:" + ex.Message);
         logger.Log("Stack Trace: " + ex.StackTrace);
     }
 }
        public void Detect_FullProfileMatch_Version()
        {
            // Fixture setup...
            const string keyName             = "subKey";
            const string valueName           = "valueName";
            var          value               = 1;
            const bool   fullProfileDetected = true;

            var expectedVersion = new DotNetVersion(new Version("1.0"));
            var builder         = MockRepository
                                  .GeneratePartialMock <DotNetVersionBuilder>();

            builder.Expect(b => b.DotNetVersion).Return(expectedVersion);

            var spec = MockRepository
                       .GeneratePartialMock <RegistryDetection>();

            spec.Expect(s => s.Validate());
            spec.Expect(s => s.FullProfileRegistryKeyName).Return(keyName);
            spec.Expect(s => s.FullProfileValueName).Return(valueName);
            spec.Expect(s => s.FullProfileValue).Return(value);
            spec.Expect(s => s.FullProfileDetected   = fullProfileDetected);
            spec.Expect(s => s.ClientProfileDetected = true);
            spec.Expect(s => s.VersionBuilder).Return(builder);

            var key = MockRepository.GenerateMock <RegistryKeyBase>(
                RegistryHive.PerformanceData
                );

            key
            .Expect(d => d.MatchRegistryValue(keyName, valueName, value))
            .Return(fullProfileDetected);

            // Exercise SUT...
            var actualVersion = spec.Detect(key);

            // Verify SUT...
            spec.VerifyAllExpectations();
            key.VerifyAllExpectations();
            Assert.That(actualVersion, Is.SameAs(expectedVersion));

            // Fixture teardown by GC...
        }
Example #26
0
        public void VersionsDelegatesToCurrentDetector()
        {
            // Fixture setup...
            var expectedVersions = new DotNetVersion[0];
            var detector         = MockRepository.GenerateMock <IDetector>();

            detector.Expect(d => d.Versions).Return(expectedVersions);
            Detector.Current = detector;

            // Exercise SUT...
            var actualVersions = Detector.Versions;

            // Verify SUT...
            detector.VerifyAllExpectations();
            Assert.That(actualVersions, Is.EqualTo(expectedVersions));

            // Fixture teardown...
            Detector.Current = null;
        }
Example #27
0
        public void CtorWithoutPacksDefaultsToEmptyPackList()
        {
            // Fixture setup...

            // Exercise SUT...
            var version = new DotNetVersion(
                new Version(),
                DotNetProfiles.Client
                );

            // Verify SUT...
            Assert.That(
                version.ServicePacks,
                Is.InstanceOf <IEnumerable <Version> >()
                );
            Assert.That(version.ServicePacks.Count(), Is.EqualTo(0));

            // Fixture teardown by GC...
        }
Example #28
0
        public DotNetFrameworkVersion this[DotNetVersion version]
        {
            get
            {
                switch (version)
                {
                case DotNetVersion.v1_1:
                    return(_versions.SingleOrDefault(x => x.Version.StartsWith("1.1")));

                case DotNetVersion.v2_0:
                    return(_versions.SingleOrDefault(x => x.Version.StartsWith("2.0")));

                case DotNetVersion.v3_0:
                    return(_versions.SingleOrDefault(x => x.Version.StartsWith("3.0")));

                case DotNetVersion.v3_5:
                    return(_versions.SingleOrDefault(x => x.Version.StartsWith("3.5")));

                case DotNetVersion.v4_0:
                    return(_versions.SingleOrDefault(x => x.TargetVersion == "4.0.0"));

                case DotNetVersion.v4_0_client:
                    return(_versions.SingleOrDefault(x => x.TargetVersion == "4.0.0" && x.Client));

                case DotNetVersion.v4_0_full:
                    return(_versions.SingleOrDefault(x => x.TargetVersion == "4.0.0" && x.Full));

                case DotNetVersion.v4_5:
                    return(_versions.SingleOrDefault(x => x.Version.StartsWith("4.5")));

                case DotNetVersion.v4_5_client:
                    return(_versions.SingleOrDefault(x => x.Version.StartsWith("4.5") && x.Client));

                case DotNetVersion.v4_5_full:
                    return(_versions.SingleOrDefault(x => x.Version.StartsWith("4.5") && x.Full));

                default:
                    return(null);
                }
            }
        }
Example #29
0
        public void DotNetVersion_VersionAndServicePacks_Built()
        {
            // Fixture setup...
            var version       = new Version("2.0");
            var servicePacks  = new[] { new Version("1.0") };
            var dotNetVersion = new DotNetVersion(version);
            var builder       = new DotNetVersionBuilder
            {
                Version      = version,
                ServicePacks = servicePacks
            };

            // Exercise SUT...
            var builtVersion = builder.DotNetVersion;

            // Verify SUT...
            Assert.That(builtVersion.Version, Is.SameAs(version));
            Assert.That(builtVersion.ServicePacks, Is.SameAs(servicePacks));

            // Fixture teardown by GC...
        }
Example #30
0
        /// <summary>
        /// Gets the ASP dot net version in string format from the dot net framework version
        /// </summary>
        /// <param name="version">The dot net framework version.</param>
        /// <returns>Asp.NET version in string format. Returns null if version is not supported</returns>
        private static string GetAspDotNetVersion(DotNetVersion version)
        {
            string dotNetVersion = null;

            switch (version)
            {
            case DotNetVersion.Two:
            {
                dotNetVersion = "v2.0";
                break;
            }

            case DotNetVersion.Four:
            {
                dotNetVersion = "v4.0";
                break;
            }
            }

            return(dotNetVersion);
        }
 public DotNetVersionCheck GetVersion(DotNetVersion version)
 {
     switch (version)
     {
         case DotNetVersion.DotNet1:
             return new Net1Check(this);
         case DotNetVersion.DotNet1_1:
             return new Net1_1Check(this);
         case DotNetVersion.DotNet2:
             return new Net2Check(this);
         case DotNetVersion.DotNet3:
             return new Net3Check(this);
         case DotNetVersion.DotNet3_5:
             return new Net3_5Check(this);
         case DotNetVersion.DotNet4:
             return new Net4Check(this);
         case DotNetVersion.DotNet4_5:
             return new Net4_5Check(this);
         default:
             return new NullDotNetVersion(this);
     }
 }
        /// <summary>
        /// sets the initial data for an application
        /// </summary>
        /// <param name="variables">All variables needed to run the application.</param>
        public void ConfigureApplication(ApplicationVariable[] variables)
        {
            try
            {
                ApplicationParsedData parsedData = PluginHelper.GetParsedData(variables);
                this.startupLogger = new FileLogger(parsedData.StartupLogFilePath);

                this.appName = RemoveSpecialCharacters(parsedData.AppInfo.Name) + parsedData.AppInfo.Port.ToString(CultureInfo.InvariantCulture);
                this.appPath = parsedData.AppInfo.Path;

                this.applicationInfo = parsedData.AppInfo;

                this.autoWireTemplates = parsedData.AutoWireTemplates;

                this.aspDotNetVersion = this.GetAppVersion(this.applicationInfo);

                this.cpuTarget = this.GetCpuTarget(this.applicationInfo);

                this.AutowireApp(parsedData.AppInfo, variables, parsedData.GetServices(), parsedData.LogFilePath, parsedData.ErrorLogFilePath);
            }
            catch (Exception ex)
            {
                this.startupLogger.Error(ex.ToString());
                throw;
            }
        }
        /// <summary>
        /// Creates a per application user, sets security access rules for the application deployment directory
        /// and adds a new site to IIS without starting it
        /// </summary>
        /// <param name="appInfo">Structure that contains parameters required for deploying the application.</param>
        /// <param name="version">The dot net framework version supported by the application.</param>
        private void DeployApp(ApplicationInfo appInfo, DotNetVersion version)
        {
            this.startupLogger.Info(Strings.DeployingAppOnIis);

            string aspNetVersion = GetAspDotNetVersion(version);
            string password = appInfo.WindowsPassword;
            string userName = appInfo.WindowsUserName;

            try
            {
                mut.WaitOne();
                using (ServerManager serverMgr = new ServerManager())
                {
                    DirectoryInfo deploymentDir = new DirectoryInfo(appInfo.Path);

                    DirectorySecurity deploymentDirSecurity = deploymentDir.GetAccessControl();

                    deploymentDirSecurity.SetAccessRule(
                        new FileSystemAccessRule(
                            userName,
                            FileSystemRights.Write | FileSystemRights.Read | FileSystemRights.Delete | FileSystemRights.Modify,
                            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                            PropagationFlags.None,
                            AccessControlType.Allow));

                    deploymentDir.SetAccessControl(deploymentDirSecurity);

                    Site mySite = serverMgr.Sites.Add(this.appName, appInfo.Path, appInfo.Port);

                    mySite.ApplicationDefaults.EnabledProtocols = "http,net.tcp";

                    mySite.Bindings[0].BindingInformation = string.Format(CultureInfo.InvariantCulture, "{0}:{1}:", appInfo.LocalIP, appInfo.Port);

                    // Disable net.tcp bindings to allow the app to bind to that TCP port.
                    mySite.ServerAutoStart = false;

                    ApplicationPool applicationPool = serverMgr.ApplicationPools[this.appName];
                    if (applicationPool == null)
                    {
                        serverMgr.ApplicationPools.Add(this.appName);
                        applicationPool = serverMgr.ApplicationPools[this.appName];
                        applicationPool.ManagedRuntimeVersion = aspNetVersion;
                        applicationPool.ProcessModel.IdentityType = ProcessModelIdentityType.SpecificUser;
                        applicationPool.ProcessModel.UserName = userName;
                        applicationPool.ProcessModel.Password = password;
                        applicationPool.ProcessModel.LoadUserProfile = true;
                        if (this.cpuTarget == CpuTarget.X86)
                        {
                            applicationPool.Enable32BitAppOnWin64 = true;
                        }
                        else
                        {
                            applicationPool.Enable32BitAppOnWin64 = false;
                        }
                    }

                    mySite.Applications["/"].ApplicationPoolName = this.appName;
                    FirewallTools.OpenPort(appInfo.Port, appInfo.Name);
                    FirewallTools.OpenPort(IISTunnelPlugin.GetNetTcpPort(appInfo.Path), appInfo.Name);
                    serverMgr.CommitChanges();
                }
            }
            finally
            {
                mut.ReleaseMutex();
                this.startupLogger.Info(Strings.FinishedAppDeploymentOnIis);
            }
        }
        /// <summary>
        /// Gets the ASP dot net version in string format from the dot net framework version
        /// </summary>
        /// <param name="version">The dot net framework version.</param>
        /// <returns>Asp.NET version in string format. Returns null if version is not supported</returns>
        private static string GetAspDotNetVersion(DotNetVersion version)
        {
            string dotNetVersion = null;
            switch (version)
            {
                case DotNetVersion.Two:
                    {
                        dotNetVersion = "v2.0";
                        break;
                    }

                case DotNetVersion.Four:
                    {
                        dotNetVersion = "v4.0";
                        break;
                    }
            }

            return dotNetVersion;
        }
Example #35
0
        /// <summary>
        /// Packs the provided assembly using the chosen .NET framework.
        /// </summary>
        /// <param name="assembly">A byte[] array containing the original assemly</param>
        /// <param name="version">The version of the .NET framework used.</param>
        /// <returns>a byte[] array containing the packed assembly</returns>
        public static byte[] Pack(byte[] assembly, DotNetVersion version)
        {
            RijndaelManaged rijndael = new RijndaelManaged();
            rijndael.KeySize = 256;
            rijndael.GenerateIV();
            rijndael.GenerateKey();

            string key = Convert.ToBase64String(rijndael.Key);
            string iv = Convert.ToBase64String(rijndael.IV);
            string app = "";

            MemoryStream memoryStream = new MemoryStream();

            rijndael.Padding = PaddingMode.ISO10126;

            CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndael.CreateEncryptor(), CryptoStreamMode.Write);
            cryptoStream.Write(assembly, 0, assembly.Length);
            cryptoStream.FlushFinalBlock();
            cryptoStream.Flush();
            memoryStream.Seek(0, SeekOrigin.Begin);
            app = Convert.ToBase64String(memoryStream.ToArray());
            cryptoStream.Close();
            memoryStream.Close();

            string csharpcode = netcrypt.Properties.Resources.StubCode;

            csharpcode = csharpcode.Replace("%KEY%", key);
            csharpcode = csharpcode.Replace("%IV%", iv);
            csharpcode = csharpcode.Replace("%PROGRAM%", app);

            Assembly orig = Assembly.Load(assembly);

            var providerOptions = new Dictionary<string, string>();

            switch (version)
            {
                case DotNetVersion.v4_0:
                    providerOptions.Add("CompilerVersion", "v4.0");
                    break;
                case DotNetVersion.v3_5:
                    providerOptions.Add("CompilerVersion", "v3.5");
                    break;
                case DotNetVersion.v2_0:
                default:
                    providerOptions.Add("CompilerVersion", "v4.0");
                    break;
            }

            CSharpCodeProvider codeProvider = new CSharpCodeProvider(providerOptions);

            CompilerParameters parameters = new CompilerParameters();

            parameters.CompilerOptions = "/target:winexe";

            AssemblyName[] names = orig.GetReferencedAssemblies();

            foreach (AssemblyName name in names)
            {
                if (name.Name.Contains("System.") ||
                    name.Name.Contains("Microsoft."))
                    parameters.ReferencedAssemblies.Add(name.Name + ".dll");
            }

            string tempFile = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".exe";

            parameters.GenerateExecutable = true;
            parameters.OutputAssembly = tempFile;

            CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, csharpcode);

            try {
                FileStream fs = results.CompiledAssembly.GetFiles()[0];
                byte[] barr  = new byte[fs.Length];
                int r = fs.Read(barr, 0, barr.Length);
                fs.Close();
                string fileName = fs.Name;
                fs.Dispose();

                if (r == barr.Length)
                {
                    return barr;
                }
                else
                {
                    return null;
                }
            } catch {

                return null;
            }
        }
Example #36
0
        /// <summary>
        /// Creates a per application user, sets security access rules for the application deployment directory
        /// and adds a new site to IIS without starting it
        /// </summary>
        /// <param name="appInfo">Structure that contains parameters required for deploying the application.</param>
        /// <param name="version">The dot net framework version supported by the application.</param>
        private void DeployApp(ApplicationInfo appInfo, DotNetVersion version)
        {
            this.startupLogger.Info(Strings.DeployingAppOnIis);

            string aspNetVersion = GetAspDotNetVersion(version);
            string password = appInfo.WindowsPassword;
            string userName = appInfo.WindowsUserName;

            try
            {
                mut.WaitOne();
                using (ServerManager serverMgr = new ServerManager())
                {
                    DirectoryInfo deploymentDir = new DirectoryInfo(appInfo.Path);

                    DirectorySecurity deploymentDirSecurity = deploymentDir.GetAccessControl();

                    deploymentDirSecurity.SetAccessRule(
                        new FileSystemAccessRule(
                            userName,
                            FileSystemRights.Write | FileSystemRights.Read | FileSystemRights.Delete | FileSystemRights.Modify,
                            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                            PropagationFlags.None,
                            AccessControlType.Allow));

                    deploymentDir.SetAccessControl(deploymentDirSecurity);

                    Site mySite = serverMgr.Sites.Add(this.appName, appInfo.Path, appInfo.Port);
                    mySite.ServerAutoStart = false;

                    ApplicationPool applicationPool = serverMgr.ApplicationPools[this.appName];
                    if (applicationPool == null)
                    {
                        serverMgr.ApplicationPools.Add(this.appName);
                        applicationPool = serverMgr.ApplicationPools[this.appName];
                        applicationPool.ManagedRuntimeVersion = aspNetVersion;
                        applicationPool.ProcessModel.IdentityType = ProcessModelIdentityType.SpecificUser;
                        applicationPool.ProcessModel.UserName = userName;
                        applicationPool.ProcessModel.Password = password;
                        if (this.cpuTarget == CpuTarget.X86)
                        {
                            applicationPool.Enable32BitAppOnWin64 = true;
                        }
                        else
                        {
                            applicationPool.Enable32BitAppOnWin64 = false;
                        }
                    }

                    mySite.Applications["/"].ApplicationPoolName = this.appName;
                    FirewallTools.OpenPort(appInfo.Port, appInfo.Name);
                    serverMgr.CommitChanges();
                }
            }
            finally
            {
                mut.ReleaseMutex();
                this.startupLogger.Info(Strings.FinishedAppDeploymentOnIis);
            }
        }