Ejemplo n.º 1
0
 public PreviewWindowModel(
     IEnumerable<PackageAction> actions, 
     Installation.InstallationTarget target)
 {
     _previewResults = PreviewResult.CreatePreview(actions, target);
     Title = Resources.Resources.WindowTitle_Preview;
 }
        void Operation.Execute( Installation genericInstallation, OperationResult operationResult )
        {
            var installation = genericInstallation as RecognizedDevelopmentInstallation;
            var localNuGetFeedFolderPath = EwlStatics.CombinePaths( ConfigurationStatics.RedStaplerFolderPath, "Local NuGet Feed" );

            // NuGet.exe has problems if the folder doesn't exist.
            Directory.CreateDirectory( localNuGetFeedFolderPath );

            ExportLogic.CreateEwlNuGetPackage( installation, true, localNuGetFeedFolderPath, null );
        }
        void Operation.Execute( Installation genericInstallation, OperationResult operationResult )
        {
            if( !ConfigurationLogic.NDependIsPresent )
                throw new UserCorrectableException( "NDepend is not present." );
            var installation = genericInstallation as DevelopmentInstallation;
            var locCount = GetNDependLocCount( installation, true );

            Console.WriteLine();
            Console.WriteLine( "LOGIC SIZE (in size points)" );
            Console.WriteLine( locCount );
            Console.WriteLine();
        }
        public static void getInstallationDetails()
        {
            InstallationDetails request = new InstallationDetails
            {
                Id = INSTALLATION_ID
            };

            InstallationDetailsResponse response = client.Get(request);

            installationDetails = response.Installation;

            Console.WriteLine("Installation Name: " + response.Installation.Name + " Owner Id: " + response.Installation.OwnerId);
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Ensure that ArchiveService is properly installed on each run, attempting to make ".NET File Copy Deployment" a reality.
 /// </summary>
 /// <remarks>
 /// This was stolen from MSR.LST.Net.Rtp.  See Notes on bugs in this design in MSR.LST.Net.Rtp.RtpSession.Install
 /// </remarks>
 private static void Install()
 {
     // Get the installed state out of the registry -- if we're already installed, we don't have to reinstall
     if (Installation.Installed == false)
     {
         // Install myself
         IDictionary state = new Hashtable();
         state.Clear();
         Installation inst = new Installation();
         inst.Install(state);
         inst.Commit(state);
     }
 }
        // GET: Installations/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Installation installation = db.Installations.Find(id);

            if (installation == null)
            {
                return(HttpNotFound());
            }
            return(View(installation));
        }
        public ActionResult Create([Bind(Include = "ReportID,ClientName,BranchName,BranchNo,Address,Store_Manager,Tel,Fax,Email,Type,Antennas,Serial,Mental_Detector,Remote,Enterance1,Distance1,Enterance2,Distance2,Enterance3,Distance3,Enterance4,Distance4,Q1,Make,Lockable,Q2,Strength,TQ1,TType1,TQ2,TType2,TQ3,TType3,TQ4,TType4,Cable,Grouting,PPU,PPA,Power_Points,DB_Labelled,Comments1,Completion,SinedC,SignedD,Screen_Shots,Staff_Training_Conduct,Comment2,Name,Signature,Place,Date")] Installation installation)
        {
            DateTime datecreated2 = DateTime.Now;

            if (ModelState.IsValid)
            {
                installation.Date = datecreated2;
                db.Installations.Add(installation);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(installation));
        }
Ejemplo n.º 8
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            string hubName = req.Query["hubName"];

            hubName = hubName ?? data?.hubName;
            if (hubName == null)
            {
                return(new BadRequestObjectResult("Please pass a Hub name (\"hubName\") on the query string or in the request body"));
            }
            string token = req.Query["token"];

            token = token ?? data?.token;
            if (token == null)
            {
                return(new BadRequestObjectResult("Please pass a token (\"token\") on the query string or in the request body"));
            }
            string tags = req.Query["tags"];

            tags = tags ?? data?.tags;
            var hub = NotificationHubClient.CreateClientFromConnectionString(
                Parameters.ConnectionString,
                hubName);

            Installation installation = new Installation();

            installation.InstallationId = Guid.NewGuid().ToString();
            installation.Platform       = NotificationPlatform.Apns;
            installation.PushChannel    = token;
            if (tags != null)
            {
                string[] tagArray = tags.Split(',');
                ArraySegment <string> tagsList = new ArraySegment <string>(tagArray);
                installation.Tags = tagsList;
            }
            try{
                hub.CreateOrUpdateInstallation(installation);
                string response = $"{{ \"installationId\" = \"{installation.InstallationId}\" }}";

                return((ActionResult) new OkObjectResult(response));
            }catch (Exception e) {
                return(new BadRequestObjectResult(e.Message));
            }
        }
Ejemplo n.º 9
0
        public bool Publish()
        {
            // old style services
            foreach (var srv in Installation.GetInstalledServices())
            {
                if (!ZeroconfDiscoverer.serviceTypes.ContainsKey(srv.ToWebService()))
                {
                    continue;
                }

                Dictionary <string, string> additionalData = new Dictionary <string, string>();
                additionalData["hwAddr"]       = String.Join(";", NetworkInformation.GetMACAddresses());
                additionalData["netbios-name"] = System.Environment.MachineName;
                additionalData["external-ip"]  = ExternalAddress.GetAddress();

                NetService net = new NetService(ZeroconfDiscoverer.DOMAIN, ZeroconfDiscoverer.serviceTypes[srv.ToWebService()], Configuration.Services.GetServiceName(), srv.Port);
                net.AllowMultithreadedCallbacks = true;
                net.TXTRecordData         = NetService.DataFromTXTRecordDictionary(additionalData);
                net.DidPublishService    += new NetService.ServicePublished(PublishedService);
                net.DidNotPublishService += new NetService.ServiceNotPublished(FailedToPublishService);
                net.Publish();
                publishedServices.Add(net);
            }

            // new style service sets
            foreach (WebServiceSet set in Detector.CreateSetComposer().ComposeUnique())
            {
                Log.Debug("Publishing service set {0}", set);
                Dictionary <string, string> additionalData = new Dictionary <string, string>();
                additionalData["mac"]          = String.Join(";", NetworkInformation.GetMACAddresses());
                additionalData["netbios-name"] = System.Environment.MachineName;
                additionalData["external-ip"]  = ExternalAddress.GetAddress();
                additionalData["mas"]          = set.MAS != null ? set.MAS : String.Empty;
                additionalData["masstream"]    = set.MASStream != null ? set.MASStream : String.Empty;
                additionalData["tas"]          = set.TAS != null ? set.TAS : String.Empty;
                additionalData["tasstream"]    = set.TASStream != null ? set.TASStream : String.Empty;
                additionalData["ui"]           = set.UI != null ? set.UI : String.Empty;

                NetService net = new NetService(ZeroconfDiscoverer.DOMAIN, SET_SERVICE_TYPE, Configuration.Services.GetServiceName(), Configuration.Services.Port);
                net.AllowMultithreadedCallbacks = true;
                net.TXTRecordData         = NetService.DataFromTXTRecordDictionary(additionalData);
                net.DidPublishService    += new NetService.ServicePublished(PublishedService);
                net.DidNotPublishService += new NetService.ServiceNotPublished(FailedToPublishService);
                net.Publish();
                publishedServices.Add(net);
            }

            return(true);
        }
        public async Task <IActionResult> Post(DeviceRegistration device)
        {
            // New registration, execute cleanup
            if (device.RegistrationId == null && device.Handle != null)
            {
                var registrations = await _hub.GetRegistrationsByChannelAsync(device.Handle, 100);

                foreach (var registration in registrations)
                {
                    await _hub.DeleteRegistrationAsync(registration);
                }

                device.RegistrationId = await _hub.CreateRegistrationIdAsync();
            }

            // ready to registration
            // ...

            RegistrationDescription deviceRegistration = null;

            switch (device.Platform)
            {
            // ...
            case "apns":
                deviceRegistration = new AppleRegistrationDescription(device.Handle);
                break;
                //...
            }

            deviceRegistration.RegistrationId = device.RegistrationId;

            deviceRegistration.Tags = new HashSet <string>(device.Tags);

            // Get the user email depending on the current identity provider
            deviceRegistration.Tags.Add($"username:{GetCurrentUser()}");

            await _hub.CreateOrUpdateRegistrationAsync(deviceRegistration);

            var deviceInstallation = new Installation();

            // ... populate fields
            deviceInstallation.Templates = new Dictionary <string, InstallationTemplate>();
            deviceInstallation.Templates.Add("type:Welcome", new InstallationTemplate
            {
                Body = "{\"aps\": {\"alert\" : \"Hi ${FullName} welcome to Auctions!\" }}"
            });

            return(Ok());
        }
    public async Task Integration()
    {
        await Installation.Run();

        var endpoint = await Program.StartEndpoint();

        await SubmitMultipartForm();

        if (!resetEvent.WaitOne(TimeSpan.FromSeconds(5)))
        {
            throw new Exception("OutgoingMessage not received");
        }

        await endpoint.Stop();
    }
        private void btnConfirmerInstallation_Click(object sender, EventArgs e)
        {
            if (grdInstallation.SelectedRows.Count == 0 || grdInstallation.SelectedRows[0].Cells[0].Value == null)
            {
                return;
            }
            int          numéro       = Util.StringToInt(grdInstallation.SelectedRows[0].Cells[0].Value.ToString());
            Installation installation = clientService.GetInstallationById(numéro);

            installation.dateRéalisation = DateTime.Now;

            clientService.UpdateInstallation(installation);
            txtDateRealisation.Text = DateTime.Now.ToString();
            MessageBox.Show("installation confirmée \n " + DateTime.Now.ToString());
        }
Ejemplo n.º 13
0
        public static async Task Trigger(
            [QueueTrigger("openprmessage")] OpenPrMessage openPrMessage,
            [Table("installation", "{InstallationId}", "{RepoName}")] Installation installation,
            [Table("pull")] ICollector <Pr> prs,
            ILogger logger,
            ExecutionContext context)
        {
            var storageAccount            = CloudStorageAccount.Parse(KnownEnvironmentVariables.AzureWebJobsStorage);
            var settingsTable             = storageAccount.CreateCloudTableClient().GetTableReference("settings");
            var installationTokenProvider = new InstallationTokenProvider();
            var pullRequest = new PullRequest();

            await RunAsync(openPrMessage, installation, prs, settingsTable, installationTokenProvider, pullRequest, logger, context)
            .ConfigureAwait(false);
        }
Ejemplo n.º 14
0
 private string GetVersionInfo(Installation ins)
 {
     try
     {
         if (!ins.Installed)
         {
             return("Not installed");
         }
         return(ins.ProductVersion);
     }
     catch
     {
         return("Unknown");
     }
 }
Ejemplo n.º 15
0
        public async Task <OperationResult> Create(int customerId)
        {
            await using var transaction = await _installationCheckingContext.Database.BeginTransactionAsync();

            try
            {
                var customer = await _customersContext.Customers.FirstOrDefaultAsync(c => c.Id == customerId);

                if (customer == null)
                {
                    return(new OperationDataResult <InstallationModel>(false, _localizationService.GetString("CustomerNotFound")));
                }

                var installation = new Installation()
                {
                    CompanyName     = customer.CompanyName,
                    CompanyAddress  = customer.CompanyAddress,
                    CompanyAddress2 = customer.CompanyAddress2,
                    CityName        = customer.CityName,
                    CountryCode     = customer.CountryCode,
                    ZipCode         = customer.ZipCode,
                    State           = InstallationState.NotAssigned,
                    Type            = InstallationType.Installation,
                    CadastralNumber = customer.CadastralNumber,
                    ApartmentNumber = customer.ApartmentNumber != null?customer.ApartmentNumber.ToString() : "",
                                          PropertyNumber = customer.PropertyNumber != null?customer.PropertyNumber.ToString() : "",
                                                               YearBuilt          = customer.CompletionYear,
                                                               LivingFloorsNumber = customer.FloorsWithLivingSpace,
                                                               // CadastralType = customer.CadastralType != null ? customer.CadastralType.ToString() : "",
                                                               CustomerId      = customer.Id,
                                                               CreatedByUserId = _userService.UserId,
                                                               UpdatedByUserId = _userService.UserId,
                };

                await installation.Create(_installationCheckingContext);

                await transaction.CommitAsync();

                return(new OperationResult(true, _localizationService.GetString("InstallationCreatedSuccessfully")));
            }
            catch (Exception e)
            {
                await transaction.RollbackAsync();

                Trace.TraceError(e.Message);
                return(new OperationResult(false, _localizationService.GetString("ErrorWhileCreatingInstallation")));
            }
        }
Ejemplo n.º 16
0
        private void copyInWebProjectFiles(Installation installation, WebProject webProject)
        {
            var webProjectFilesFolderPath = EwlStatics.CombinePaths(ConfigurationStatics.InstallationPath, AppStatics.WebProjectFilesFolderName);
            var webProjectPath            = EwlStatics.CombinePaths(installation.GeneralLogic.Path, webProject.name);

            // Copy Ewf folder and customize namespaces in .aspx, .ascx, .master, and .cs files.
            var webProjectEwfFolderPath = EwlStatics.CombinePaths(webProjectPath, StaticFileHandler.EwfFolderName);

            IoMethods.DeleteFolder(webProjectEwfFolderPath);
            IoMethods.CopyFolder(EwlStatics.CombinePaths(webProjectFilesFolderPath, StaticFileHandler.EwfFolderName), webProjectEwfFolderPath, false);
            IoMethods.RecursivelyRemoveReadOnlyAttributeFromItem(webProjectEwfFolderPath);
            var matchingFiles = new List <string>();

            matchingFiles.AddRange(Directory.GetFiles(webProjectEwfFolderPath, "*.aspx", SearchOption.AllDirectories));
            matchingFiles.AddRange(Directory.GetFiles(webProjectEwfFolderPath, "*.ascx", SearchOption.AllDirectories));
            matchingFiles.AddRange(Directory.GetFiles(webProjectEwfFolderPath, "*.master", SearchOption.AllDirectories));
            matchingFiles.AddRange(Directory.GetFiles(webProjectEwfFolderPath, "*.cs", SearchOption.AllDirectories));
            foreach (var filePath in matchingFiles)
            {
                File.WriteAllText(filePath, customizeNamespace(File.ReadAllText(filePath), webProject));
            }

            IoMethods.CopyFile(
                EwlStatics.CombinePaths(webProjectFilesFolderPath, AppStatics.StandardLibraryFilesFileName),
                EwlStatics.CombinePaths(webProjectPath, AppStatics.StandardLibraryFilesFileName));
            IoMethods.RecursivelyRemoveReadOnlyAttributeFromItem(EwlStatics.CombinePaths(webProjectPath, AppStatics.StandardLibraryFilesFileName));

            // Add the Import element to the project file if it's not already present.
            var projectDocument = new XmlDocument {
                PreserveWhitespace = true
            };
            var projectDocumentPath = EwlStatics.CombinePaths(webProjectPath, "{0}.csproj".FormatWith(webProject.name));

            projectDocument.Load(projectDocumentPath);
            var          projectElement          = projectDocument["Project"];
            const string webProjectFilesFileName = "Standard Library Files.xml";
            var          namespaceManager        = new XmlNamespaceManager(projectDocument.NameTable);
            const string ns = "http://schemas.microsoft.com/developer/msbuild/2003";

            namespaceManager.AddNamespace("p", ns);
            if (projectElement.SelectSingleNode("p:Import[ @Project = \"{0}\" ]".FormatWith(webProjectFilesFileName), namespaceManager) == null)
            {
                var importElement = projectDocument.CreateElement("Import", ns);
                importElement.SetAttribute("Project", webProjectFilesFileName);
                projectElement.AppendChild(importElement);
                projectDocument.Save(projectDocumentPath);
            }
        }
Ejemplo n.º 17
0
        public async Task downloads_for_installations_not_present_in_database()
        {
            // Arrange
            var downloadedData = new Installation();

            var modifiedInstallationIds = new List <short>();

            short newInstallationId = 1;

            while (_installationIds.Contains(newInstallationId))
            {
                newInstallationId++;
            }

            modifiedInstallationIds.Add(newInstallationId);
            modifiedInstallationIds.AddRange(
                _installationIds.GetRange(0, _installationIds.Count - 1));

            foreach (short installationId in _installationIds)
            {
                var exampleInstallationInfo
                    = GetTestInstallationInfo(installationId, DateTime.UtcNow.Date);

                _context.InstallationInfos.Add(exampleInstallationInfo);
            }

            _context.SaveChanges();

            _downloaderMock.Setup(x => x.DownloadAirQualityData(newInstallationId))
            .ReturnsAsync(downloadedData);

            var programController = new ProgramController(
                unitOfWork: _unitOfWork,
                installationIds: modifiedInstallationIds,
                airlyInstallationDownloader: _downloaderMock.Object);

            // Act
            var installations = await programController.DownloadInstallationInfos();

            // Assert
            _downloaderMock.Verify(
                x => x.DownloadAirQualityData(newInstallationId), Times.Once);

            _downloaderMock.Verify(
                x => x.DownloadAirQualityData(It.IsAny <short>()), Times.Once);

            Assert.Single(installations);
        }
Ejemplo n.º 18
0
        private Installation CreateDatabase(InstallConfig install)
        {
            var result = new Installation {
                Success = false, Message = string.Empty
            };

            if (install.IsNewTenant)
            {
                try
                {
                    InstallDatabase(install);

                    var databaseType = install.DatabaseType;

                    //Get database Type
                    var type = Type.GetType(databaseType);

                    //Create database object from Type
                    var database = Activator.CreateInstance(type) as IDatabase;

                    //create data directory if does not exist
                    var dataDirectory = AppDomain.CurrentDomain.GetData("DataDirectory")?.ToString();
                    if (!Directory.Exists(dataDirectory))
                    {
                        Directory.CreateDirectory(dataDirectory ?? String.Empty);
                    }

                    var dbOptions = new DbContextOptionsBuilder().UseOqtaneDatabase(database, NormalizeConnectionString(install.ConnectionString)).Options;
                    using (var dbc = new DbContext(dbOptions))
                    {
                        // create empty database if it does not exist
                        dbc.Database.EnsureCreated();
                        result.Success = true;
                    }
                }
                catch (Exception ex)
                {
                    result.Message = ex.Message;
                    _filelogger.LogError(Utilities.LogMessage(this, result.Message));
                }
            }
            else
            {
                result.Success = true;
            }

            return(result);
        }
Ejemplo n.º 19
0
        public bool Open()
        {
            try
            {
                ServiceState.RegisterStartupCondition(STARTUP_CONDITION);
                Log.Debug("Opening MPExtended ServiceHost version {0}", VersionUtil.GetFullVersionString());

                // always log uncaught exceptions that cause the program to exit
                AppDomain.CurrentDomain.UnhandledException += delegate(object sender, UnhandledExceptionEventArgs e)
                {
                    Log.Error("Unhandled exception", (Exception)e.ExceptionObject);
                    if (e.IsTerminating)
                    {
                        Log.Fatal("Terminating because of previous exception");
                    }
                };
                // start watching the configuration files for changes
                Configuration.Load();
                Configuration.EnableChangeWatching();

                // start the WCF services
                wcf.Start(Installation.GetAvailableServices().Where(x => x.WCFType != null));

                // init all services
                var services = Installation.GetAvailableServices().Where(x => x.InitClass != null && x.InitMethod != null);
                foreach (var service in services)
                {
                    BindingFlags flags = BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod;
                    service.InitClass.InvokeMember(service.InitMethod, flags, null, null, null);
                }

                // ensure a service dependency on the TVEngine is set
                Task.Factory.StartNew(TVEDependencyInstaller.EnsureDependencyIsInstalled);

                // log MP version details
                Mediaportal.LogVersionDetails();

                // finish
                ServiceState.StartupConditionCompleted(STARTUP_CONDITION);
                Log.Trace("Opened MPExtended ServiceHost");
                return(true);
            }
            catch (Exception ex)
            {
                Log.Error("Failed to open MPExtended ServiceHost", ex);
                return(false);
            }
        }
        // GET: Installations/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Installation installation = db.Installations.Find(id);

            if (installation == null)
            {
                return(HttpNotFound());
            }
            ViewBag.EquipmentId        = new SelectList(db.Equipments, "Id", "Name", installation.EquipmentId);
            ViewBag.Destination_SiteId = new SelectList(db.Sites, "Id", "Name", installation.Destination_SiteId);
            return(View(installation));
        }
 public JsonResult AddMissingEquipmentParts(int installationId)
 {
     try
     {
         Installation i = db.Installations.Find(installationId);
         foreach (var item in i.MissingParts)
         {
             AddEquipmentPart(installationId, item.Id);
         }
         return(Json(new { result = true }, JsonRequestBehavior.AllowGet));
     }
     catch (Exception)
     {
     }
     return(Json(new { result = false }, JsonRequestBehavior.AllowGet));
 }
Ejemplo n.º 22
0
        private async Task SumAsync2(int v, string key, Installation installation)
        {
            Func <Task> action = async() => await CountAsync(v);

            var dKey = new DealingKey()
            {
                Key = key
            };
            List <Task> tasks = new();

            for (int i = 0; i < 20; i++)
            {
                tasks.Add(dKey.RunUnderRaceConditionAsync(action, installation));
            }
            await Task.WhenAll(tasks);
        }
Ejemplo n.º 23
0
 public static InstallationInfo ConvertToInstallationInfo(
     this Installation installation, DateTime updateDate)
 {
     return(new InstallationInfo()
     {
         InstallationId = (short)installation.Id,
         UpdateDate = updateDate,
         Address = new Address()
         {
             Country = installation.Address.Country ?? "",
             City = installation.Address.City ?? "",
             Street = installation.Address.Street ?? "",
             Number = installation.Address.Number ?? "",
         }
     });
 }
Ejemplo n.º 24
0
        public async Task SubscribeAsync(DeviceInstallationDto installationRequest, string user)
        {
            var userId = "ANY";

            var installation = new Installation
            {
                InstallationId = installationRequest.Id,
                UserId         = user,
                PushChannel    = installationRequest.PnsHandle,
                Tags           = new[] { $"user:{userId}" },
                Platform       = NotificationPlatform.Fcm,
            };

            // call notification hubs to create a new registration ID, and then return the ID back to the device.
            await hub.CreateOrUpdateInstallationAsync(installation);
        }
Ejemplo n.º 25
0
        //--------------------------------------------------------------------
        public Installation Find(Guid ID)
        {
            Installation lInstallation = (Installation)AbstractFind(ID);

            if (Util.isNULL(lInstallation))
            {
                DataRow row = DataBase.SelectID(ID, "[Installation]");
                if (Util.isNULL(row))
                {
                    return(null);
                }
                lInstallation = this.FillFields(row);
                LoadedMap.Add(lInstallation.ID, lInstallation);
            }
            return(lInstallation);
        }
Ejemplo n.º 26
0
        public void Play(Installation i)
        {
            {
                var v = i.Version;
                switch (v.DisplayInstallStatus.ToString())
                {
                case "Not installed":
                    InvokeDownload(v);
                    break;

                case "Installed":
                    InvokeLaunch(v);
                    break;
                }
            }
        }
        /// <summary>
        /// Creates or overwrites an installation.
        /// </summary>
        /// <returns></returns>
        public async Task <string> CreateOrOverwriteInstallation(Installation installation)
        {
            HttpClient hc = GetClient($"installations/{installation?.InstallationId}");

            try
            {
                HttpResponseMessage response = await hc.PutAsync(string.Empty, new StringContent(JsonConvert.SerializeObject(installation), Encoding.UTF8, "application/json"));

                response.EnsureSuccessStatusCode();
                return(response.Headers.Location?.ToString().Replace($"{ServiceUrl}/installations/", ""));
            }
            catch (Exception e)
            {
                throw (new Exception("Error on service call", e));
            }
        }
        public DateTime?GetLatestMeasurementDateForInstallation(Installation installation)
        {
            try
            {
                var measurementItem = CurrentDbConnection.Query <MeasurementItemEntity>(
                    $"SELECT * FROM MeasurementItems INNER JOIN Measurements WHERE Measurements.InstallationId = {installation.Id} AND Measurements.CurrentId = MeasurementItems.Id ORDER BY TillDateTime DESC");

                return(measurementItem.OrderByDescending(item => item.TillDateTime.Ticks).FirstOrDefault()?.TillDateTime);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            return(null);
        }
Ejemplo n.º 29
0
        public static async Task RunAsync(
            DeleteBranchMessage deleteBranchMessage,
            Installation installation,
            IInstallationTokenProvider installationTokenProvider,
            ILogger logger,
            ExecutionContext context)
        {
            if (installation == null)
            {
                logger.LogError("No installation found for {InstallationId}", deleteBranchMessage.InstallationId);
                throw new Exception($"No installation found for InstallationId: {deleteBranchMessage.InstallationId}");
            }

            var installationToken = await installationTokenProvider.GenerateAsync(
                new InstallationTokenParameters
            {
                AccessTokensUrl = string.Format(KnownGitHubs.AccessTokensUrlFormat, installation.InstallationId),
                AppId           = KnownGitHubs.AppId,
            },
                KnownEnvironmentVariables.APP_PRIVATE_KEY);

            logger.LogInformation("DeleteBranchFunction: Deleting imgbot branch for {Owner}/{RepoName}", installation.Owner, installation.RepoName);

            var inMemoryCredentialStore = new InMemoryCredentialStore(new Octokit.Credentials(KnownGitHubs.Username, installationToken.Token));
            var githubClient            = new Octokit.GitHubClient(new Octokit.ProductHeaderValue("ImgBot"), inMemoryCredentialStore);

            var imgbotRefName = $"heads/{KnownGitHubs.BranchName}";

            Octokit.Reference imgbotBranchRef = null;
            try
            {
                imgbotBranchRef = await githubClient.Git.Reference.Get(installation.Owner, installation.RepoName, imgbotRefName);
            }
            catch
            {
            }

            if (imgbotBranchRef == null)
            {
                logger.LogInformation("DeleteBranchFunction: No imgbot branch found for {Owner}/{RepoName}", installation.Owner, installation.RepoName);
                return;
            }

            await githubClient.Git.Reference.Delete(installation.Owner, installation.RepoName, imgbotRefName);

            logger.LogInformation("DeleteBranchFunction: Successfully deleted imgbot branch for {Owner}/{RepoName}", installation.Owner, installation.RepoName);
        }
Ejemplo n.º 30
0
        public static void Run(
            [QueueTrigger("routermessage")] RouterMessage routerMessage,
            [Table("installation", "{InstallationId}", "{RepoName}")] Installation installation,
            [Table("installation")] ICollector <Installation> installations,
            [Queue("compressimagesmessage")] ICollector <CompressImagesMessage> compressImagesMessages,
            ILogger logger)
        {
            var compress = routerMessage.GetType().GetProperty("Compress") == null || routerMessage.Compress == true;

            if (installation == null)
            {
                installations.Add(new Installation(routerMessage.InstallationId, routerMessage.RepoName)
                {
                    CloneUrl    = routerMessage.CloneUrl,
                    Owner       = routerMessage.Owner,
                    LastChecked = DateTime.UtcNow,
                    IsOptimized = compress,
                    IsPrivate   = routerMessage.IsPrivate,
                });
            }
            else
            {
                installation.LastChecked = DateTime.UtcNow;
            }

            if (routerMessage.GetType().GetProperty("Update") != null && routerMessage.Update == true)
            {
                installation.IsOptimized = compress;
            }

            /*
             *  TODO: add logic for routing
             *        https://github.com/dabutvin/ImgBot/issues/98
             */
            if (compress)
            {
                compressImagesMessages.Add(new CompressImagesMessage
                {
                    CloneUrl       = routerMessage.CloneUrl,
                    InstallationId = routerMessage.InstallationId,
                    Owner          = routerMessage.Owner,
                    RepoName       = routerMessage.RepoName,
                });

                logger.LogInformation("RouterFunction: Added CompressImagesMessage for {Owner}/{RepoName}", routerMessage.Owner, routerMessage.RepoName);
            }
        }
Ejemplo n.º 31
0
        private async Task CreateOrUpdateInstallationAsync_CreateInstallationWithExpiryInTemplate_GetCreatedInstallationWithExpiryInTemplateBack()
        {
            LoadMockData();

            await DeleteAllRegistrationsAndInstallations();

            var installationId = _testServer.NewGuid().ToString();

            var installation = new Installation
            {
                InstallationId = installationId,
                Platform       = NotificationPlatform.Apns,
                PushChannel    = _configuration["AppleDeviceToken"],
                PushVariables  = new Dictionary <string, string> {
                    { "var1", "value1" }
                },
                Tags = new List <string> {
                    "tag1"
                },
                Templates = new Dictionary <string, InstallationTemplate>
                {
                    {
                        "Template Name", new InstallationTemplate
                        {
                            Body   = "{\"aps\":{\"alert\":\"alert!\"}}",
                            Expiry = DateTime.Now.AddDays(1).ToString("o")
                        }
                    }
                }
            };

            await _hubClient.CreateOrUpdateInstallationAsync(installation);

            await Sleep(TimeSpan.FromSeconds(1));

            var createdInstallation = await _hubClient.GetInstallationAsync(installationId);

            Assert.Equal(installation.InstallationId, createdInstallation.InstallationId);
            Assert.Equal(installation.Platform, createdInstallation.Platform);
            Assert.Equal(installation.PushChannel, createdInstallation.PushChannel);
            Assert.Contains(new KeyValuePair <string, string>("var1", "value1"), createdInstallation.PushVariables);
            Assert.Contains("tag1", createdInstallation.Tags);
            Assert.Contains("Template Name", createdInstallation.Templates.Keys);
            Assert.Equal(installation.Templates["Template Name"].Body, createdInstallation.Templates["Template Name"].Body);

            RecordTestResults();
        }
Ejemplo n.º 32
0
        private void OnStartup(object sender, StartupEventArgs e)
        {
            // make sure to start only once
            if (!mutex.WaitOne(TimeSpan.Zero, true))
            {
                UserServices.Private.OpenConfigurator();
                this.Shutdown(0);
                return;
            }

            // defaults
            StartupArguments.RunAsTrayApp = true;
            StartupArguments.OpenOnStart  = false;

            // parse command line arguments
            foreach (string arg in e.Args)
            {
                switch (arg)
                {
                case "/Tray":
                    StartupArguments.RunAsTrayApp = true;
                    break;

                case "/NoTray":
                case "/OnlyConfigurator":
                    StartupArguments.RunAsTrayApp = false;
                    StartupArguments.OpenOnStart  = true;
                    break;

                case "/Open":
                    StartupArguments.OpenOnStart = true;
                    break;

                default:
                    Log.Warn("Unknown command-line parameter {0}", arg);
                    break;
                }
            }

#if !DEBUG
            // change to installation directory
            Environment.CurrentDirectory = Installation.GetInstallDirectory(MPExtendedProduct.Service);
#endif

            // set startup form
            this.StartupUri = new Uri("MainWindow.xaml", UriKind.Relative);
        }
        public async Task RegisterAsync(RegistrationRequest request)
        {
            Installation installation = new Installation
            {
                InstallationId = request.trackingNumber,
                PushChannel    = request.trackingNumber,
                Tags           = new List <string>()
                {
                    request.trackingNumber
                },
                Platform = NotificationPlatform.Fcm
            };

            await _hub.CreateOrUpdateInstallationAsync(installation);

            return;
        }
Ejemplo n.º 34
0
        public async Task <IActionResult> getInstallation(string name)
        {
            string json;

            try
            {
                Installation inst = await cc.GetInstallationAsync(name);

                json = JsonSerializer.Serialize(inst);
            }
            catch (Exception e)
            {
                return(BadRequest(e.StackTrace));
            }

            return(Ok(json));
        }
        public Installation Post([FromBody] InstallConfig config)
        {
            var installation = new Installation {
                Success = false, Message = ""
            };

            if (ModelState.IsValid && (User.IsInRole(Constants.HostRole) || string.IsNullOrEmpty(_config.GetConnectionString(SettingKeys.ConnectionStringKey))))
            {
                installation = _databaseManager.Install(config);
            }
            else
            {
                installation.Message = "Installation Not Authorized";
            }

            return(installation);
        }
Ejemplo n.º 36
0
        public static IEnumerable<PreviewResult> CreatePreview(
            IEnumerable<NuGet.Client.Resolution.PackageAction> actions,
            Installation.InstallationTarget target)
        {
            var previewResults = new List<PreviewResult>();

            foreach (var targetProject in target.GetAllTargetsRecursively())
            {
                var result = CalculatePreviewForProject(actions, targetProject);

                if (result != null)
                {
                    previewResults.Add(result);
                }
            }

            return previewResults;
        }
 bool Operation.IsValid( Installation installation )
 {
     return installation is DevelopmentInstallation;
 }
Ejemplo n.º 38
0
 /// <summary>
 /// If licenseType is a beta license, returns true. A beta license grants
 /// full use of the product during the pre-release development period.
 /// </summary>
 /// <param name="licenseType"></param>
 /// <seealso cref="Installation"/>
 /// <returns>true if licenseType is a beta license. false otherwise</returns>
 public static bool IsInstallationBeta(Installation licenseType)
 {
   return (licenseType == Installation.Beta || licenseType == Installation.BetaLab);
 }
        internal Installation CreateInstallation(NotificationInstallation notificationInstallation)
        {
            if (notificationInstallation == null)
            {
                throw new ArgumentNullException("notificationInstallation");
            }

            if (notificationInstallation.Platform == null)
            {
                throw new ArgumentException("notificationInstallation.Platform is null");
            }

            Installation installation = new Installation();
            installation.InstallationId = notificationInstallation.InstallationId;
            installation.PushChannel = notificationInstallation.PushChannel;

            // Set the Platform. Create and add WnsSecondaryTile objects to the installation if WNS.
            if (notificationInstallation.Platform.Equals(WindowsStorePlatform, StringComparison.OrdinalIgnoreCase))
            {
                installation.Platform = NotificationPlatform.Wns;

                // Parse each Secondary Tile passed in request and add to installation object.
                foreach (string tileName in notificationInstallation.SecondaryTiles.Keys)
                {
                    NotificationSecondaryTile notificationTile = notificationInstallation.SecondaryTiles[tileName];
                    if (installation.SecondaryTiles == null)
                    {
                        installation.SecondaryTiles = new Dictionary<string, WnsSecondaryTile>();
                    }

                    installation.SecondaryTiles[tileName] = CreateWnsSecondaryTile(notificationTile);
                }
            }
            else if (notificationInstallation.Platform.Equals(ApplePlatform, StringComparison.OrdinalIgnoreCase))
            {
                installation.Platform = NotificationPlatform.Apns;
            }
            else if (notificationInstallation.Platform.Equals(GooglePlatform, StringComparison.OrdinalIgnoreCase))
            {
                installation.Platform = NotificationPlatform.Gcm;
            }
            else
            {
                throw new HttpResponseException(this.Request.CreateBadRequestResponse(RResources.NotificationHub_UnsupportedPlatform.FormatForUser(notificationInstallation.Platform)));
            }

            // Create and add InstallationTemplate objects to the installation.
            foreach (string templateName in notificationInstallation.Templates.Keys)
            {
                NotificationTemplate template = notificationInstallation.Templates[templateName];
                if (installation.Templates == null)
                {
                    installation.Templates = new Dictionary<string, InstallationTemplate>();
                }

                installation.Templates[templateName] = CreateInstallationTemplate(template, installation.Platform);
            }

            return installation;
        }
        protected virtual async Task UpsertInstallationAsync(Installation installation)
        {
            if (installation == null)
            {
                throw new ArgumentNullException("installation");
            }

            if (installation.InstallationId == null)
            {
                throw new ArgumentNullException("installation.InstallationId");
            }

            if (installation.PushChannel == null)
            {
                throw new ArgumentNullException("installation.PushChannel");
            }

            // NH client will validate the Installation.InstallationId value.
            await this.PushClient.CreateOrUpdateInstallationAsync(installation);
        }
Ejemplo n.º 41
0
 public void ExecuteScript(string packageInstallPath, string scriptRelativePath, object package, Installation.InstallationTarget target)
 {
     var executor = new VsPowerShellScriptExecutor(ServiceLocator.GetInstance<IScriptExecutor>());
     executor.ExecuteScript(packageInstallPath, scriptRelativePath, package, target, this);
 }
        public virtual Task CreateOrUpdateInstallationAsync(Installation installation)
        {
            if (installation == null)
            {
                throw new ArgumentNullException("installation");
            }

            return this.HubClient.CreateOrUpdateInstallationAsync(installation);
        }
Ejemplo n.º 43
0
 /// <summary>
 /// If licenseType is a commercial license, returns true. A commercial license grants
 /// full use of the product.
 /// </summary>
 /// <param name="licenseType"></param>
 /// <seealso cref="Installation"/>
 /// <returns>true if licenseType is a commercial license. false otherwise</returns>
 public static bool IsInstallationCommercial(Installation licenseType)
 {
   return (licenseType == Installation.Commercial     ||
           licenseType == Installation.Corporate      ||
           licenseType == Installation.Educational    ||
           licenseType == Installation.EducationalLab ||
           licenseType == Installation.NotForResale   ||
           licenseType == Installation.NotForResaleLab);
 }
        private void copyInWebProjectFiles( Installation installation, WebProject webProject )
        {
            var webProjectFilesFolderPath = EwlStatics.CombinePaths( ConfigurationStatics.InstallationPath, AppStatics.WebProjectFilesFolderName );
            var webProjectPath = EwlStatics.CombinePaths( installation.GeneralLogic.Path, webProject.name );

            // Copy Ewf folder and customize namespaces in .aspx, .ascx, .master, and .cs files.
            var webProjectEwfFolderPath = EwlStatics.CombinePaths( webProjectPath, StaticFileHandler.EwfFolderName );
            IoMethods.DeleteFolder( webProjectEwfFolderPath );
            IoMethods.CopyFolder( EwlStatics.CombinePaths( webProjectFilesFolderPath, StaticFileHandler.EwfFolderName ), webProjectEwfFolderPath, false );
            IoMethods.RecursivelyRemoveReadOnlyAttributeFromItem( webProjectEwfFolderPath );
            var matchingFiles = new List<string>();
            matchingFiles.AddRange( Directory.GetFiles( webProjectEwfFolderPath, "*.aspx", SearchOption.AllDirectories ) );
            matchingFiles.AddRange( Directory.GetFiles( webProjectEwfFolderPath, "*.ascx", SearchOption.AllDirectories ) );
            matchingFiles.AddRange( Directory.GetFiles( webProjectEwfFolderPath, "*.master", SearchOption.AllDirectories ) );
            matchingFiles.AddRange( Directory.GetFiles( webProjectEwfFolderPath, "*.cs", SearchOption.AllDirectories ) );
            foreach( var filePath in matchingFiles )
                File.WriteAllText( filePath, customizeNamespace( File.ReadAllText( filePath ), webProject ) );

            IoMethods.CopyFile(
                EwlStatics.CombinePaths( webProjectFilesFolderPath, AppStatics.StandardLibraryFilesFileName ),
                EwlStatics.CombinePaths( webProjectPath, AppStatics.StandardLibraryFilesFileName ) );
            IoMethods.RecursivelyRemoveReadOnlyAttributeFromItem( EwlStatics.CombinePaths( webProjectPath, AppStatics.StandardLibraryFilesFileName ) );

            // Add the Import element to the project file if it's not already present.
            var projectDocument = new XmlDocument { PreserveWhitespace = true };
            var projectDocumentPath = EwlStatics.CombinePaths( webProjectPath, "{0}.csproj".FormatWith( webProject.name ) );
            projectDocument.Load( projectDocumentPath );
            var projectElement = projectDocument[ "Project" ];
            const string webProjectFilesFileName = "Standard Library Files.xml";
            var namespaceManager = new XmlNamespaceManager( projectDocument.NameTable );
            const string ns = "http://schemas.microsoft.com/developer/msbuild/2003";
            namespaceManager.AddNamespace( "p", ns );
            if( projectElement.SelectSingleNode( "p:Import[ @Project = \"{0}\" ]".FormatWith( webProjectFilesFileName ), namespaceManager ) == null ) {
                var importElement = projectDocument.CreateElement( "Import", ns );
                importElement.SetAttribute( "Project", webProjectFilesFileName );
                projectElement.AppendChild( importElement );
                projectDocument.Save( projectDocumentPath );
            }
        }
        internal static void AddTagToInstallation(Installation installation, string tag)
        {
            if (installation.Tags == null)
            {
                installation.Tags = new List<string>();
            }

            installation.Tags.Add(tag);
        }
        void Operation.Execute( Installation genericInstallation, OperationResult operationResult )
        {
            var installation = genericInstallation as DevelopmentInstallation;

            var logicPackagesFolderPath = EwlStatics.CombinePaths( installation.GeneralLogic.Path, "Logic Packages" );
            IoMethods.DeleteFolder( logicPackagesFolderPath );

            // Set up the main (build) object in the build message.
            var build = new InstallationSupportUtility.RsisInterface.Messages.BuildMessage.Build();
            build.SystemName = installation.ExistingInstallationLogic.RuntimeConfiguration.SystemName;
            build.SystemShortName = installation.ExistingInstallationLogic.RuntimeConfiguration.SystemShortName;
            build.MajorVersion = installation.CurrentMajorVersion;
            build.BuildNumber = installation.NextBuildNumber;
            build.LogicSize = ConfigurationLogic.NDependIsPresent && !installation.DevelopmentInstallationLogic.SystemIsEwl
                                  ? GetLogicSize.GetNDependLocCount( installation, false ) as int?
                                  : null;
            var serverSideLogicFolderPath = EwlStatics.CombinePaths( logicPackagesFolderPath, "Server Side Logic" );
            packageWebApps( installation, serverSideLogicFolderPath );
            packageWindowsServices( installation, serverSideLogicFolderPath );
            packageServerSideConsoleApps( installation, serverSideLogicFolderPath );
            packageGeneralFiles( installation, serverSideLogicFolderPath, true );
            build.ServerSideLogicPackage = ZipOps.ZipFolderAsByteArray( serverSideLogicFolderPath );
            operationResult.NumberOfBytesTransferred = build.ServerSideLogicPackage.LongLength;

            // Set up the client side application object in the build message, if necessary.
            if( installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject != null ) {
                build.ClientSideApp = new InstallationSupportUtility.RsisInterface.Messages.BuildMessage.Build.ClientSideAppType();
                build.ClientSideApp.Name = installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject.name;
                build.ClientSideApp.AssemblyName = installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject.assemblyName;
                var clientSideAppFolder = EwlStatics.CombinePaths( logicPackagesFolderPath, "Client Side Application" );
                packageClientSideApp( installation, clientSideAppFolder );
                packageGeneralFiles( installation, clientSideAppFolder, false );
                build.ClientSideApp.Package = ZipOps.ZipFolderAsByteArray( clientSideAppFolder );
                operationResult.NumberOfBytesTransferred += build.ClientSideApp.Package.LongLength;
            }

            // Set up the list of installation objects in the build message.
            build.Installations = new InstallationSupportUtility.RsisInterface.Messages.BuildMessage.Build.InstallationsType();
            foreach( var installationConfigurationFolderPath in
                Directory.GetDirectories(
                    EwlStatics.CombinePaths(
                        installation.ExistingInstallationLogic.RuntimeConfiguration.ConfigurationFolderPath,
                        InstallationConfiguration.InstallationConfigurationFolderName,
                        InstallationConfiguration.InstallationsFolderName ) ) ) {
                if( Path.GetFileName( installationConfigurationFolderPath ) != InstallationConfiguration.DevelopmentInstallationFolderName ) {
                    var buildMessageInstallation = new InstallationSupportUtility.RsisInterface.Messages.BuildMessage.Installation();

                    // Do not perform schema validation since the schema file on disk may not match this version of the ISU.
                    var installationConfigurationFile =
                        XmlOps.DeserializeFromFile<InstallationStandardConfiguration>(
                            EwlStatics.CombinePaths( installationConfigurationFolderPath, InstallationConfiguration.InstallationStandardConfigurationFileName ),
                            false );

                    buildMessageInstallation.Id = installationConfigurationFile.rsisInstallationId;
                    buildMessageInstallation.Name = installationConfigurationFile.installedInstallation.name;
                    buildMessageInstallation.ShortName = installationConfigurationFile.installedInstallation.shortName;
                    buildMessageInstallation.IsLiveInstallation = installationConfigurationFile.installedInstallation.InstallationTypeConfiguration != null
                                                                      ? installationConfigurationFile.installedInstallation.InstallationTypeConfiguration is
                                                                        LiveInstallationConfiguration
                                                                      : installationConfigurationFile.installedInstallation.IsLiveInstallation;
                    buildMessageInstallation.ConfigurationPackage = ZipOps.ZipFolderAsByteArray( installationConfigurationFolderPath );
                    build.Installations.Add( buildMessageInstallation );
                    operationResult.NumberOfBytesTransferred += buildMessageInstallation.ConfigurationPackage.LongLength;
                }
            }

            if( installation.DevelopmentInstallationLogic.SystemIsEwl )
                build.NuGetPackages = packageEwl( installation, logicPackagesFolderPath );

            var recognizedInstallation = installation as RecognizedDevelopmentInstallation;
            if( recognizedInstallation == null )
                return;

            build.SystemId = recognizedInstallation.KnownSystemLogic.RsisSystem.Id;

            operationResult.TimeSpentWaitingForNetwork = EwlStatics.ExecuteTimedRegion(
                delegate {
                    using( var memoryStream = new MemoryStream() ) {
                        // Understand that by doing this, we are not really taking advantage of streaming, but at least it will be easier to do it the right way some day (probably by implementing our own BuildMessageStream)
                        XmlOps.SerializeIntoStream( build, memoryStream );
                        memoryStream.Position = 0;

                        ConfigurationLogic.ExecuteIsuServiceMethod(
                            channel => channel.UploadBuild( new BuildUploadMessage { AuthenticationKey = ConfigurationLogic.AuthenticationKey, BuildDocument = memoryStream } ),
                            "build upload" );
                    }
                } );
        }
Ejemplo n.º 47
0
        // Calulates the prevew result for the target project and returns the result.
        private static PreviewResult CalculatePreviewForProject(
            IEnumerable<NuGet.Client.Resolution.PackageAction> actions,
            Installation.InstallationTarget targetProject)
        {
            var existingPackages = targetProject.InstalledPackages.GetInstalledPackages()
                .Select(p => p.Identity)
                .ToList();

            var installed = new Dictionary<string, PackageIdentity>(StringComparer.OrdinalIgnoreCase);
            var uninstalled = new Dictionary<string, PackageIdentity>(StringComparer.OrdinalIgnoreCase);
            foreach (var action in actions.Where(a => targetProject.Equals(a.Target)))
            {
                if (action.ActionType == PackageActionType.Install)
                {
                    installed[action.PackageIdentity.Id] = action.PackageIdentity;
                }
                else if (action.ActionType == PackageActionType.Uninstall)
                {
                    uninstalled[action.PackageIdentity.Id] = action.PackageIdentity;
                }
            }

            var addedPackages = new List<PackageIdentity>();
            var deletedPackages = new List<PackageIdentity>();
            var unchangedPackages = new List<PackageIdentity>();
            var updatedPackges = new List<UpdatePreviewResult>();

            // process existing packages to get updatedPackages, deletedPackages
            // and unchangedPackages
            foreach (var package in existingPackages)
            {
                var isInstalled = installed.ContainsKey(package.Id);
                var isUninstalled = uninstalled.ContainsKey(package.Id);

                if (isInstalled && isUninstalled)
                {
                    // the package is updated
                    updatedPackges.Add(new UpdatePreviewResult(package, installed[package.Id]));
                    installed.Remove(package.Id);
                }
                else if (isInstalled && !isUninstalled)
                {
                    // this can't happen
                    Debug.Assert(false, "We should never reach here");
                }
                else if (!isInstalled && isUninstalled)
                {
                    // the package is uninstalled
                    deletedPackages.Add(package);
                }
                else if (!isInstalled && !isUninstalled)
                {
                    // the package is unchanged
                    unchangedPackages.Add(package);
                }
            }

            // now calculate addedPackages
            foreach (var package in installed.Values)
            {
                if (!existingPackages.Contains(package))
                {
                    addedPackages.Add(package);
                }
            }

            if (addedPackages.Any() ||
                deletedPackages.Any() ||
                updatedPackges.Any())
            {
                return new PreviewResult(
                    targetProject.Name,
                    added: addedPackages,
                    deleted: deletedPackages,
                    unchanged: unchangedPackages,
                    updated: updatedPackges);
            }
            else
            {
                return null;
            }
        }
Ejemplo n.º 48
0
 /// <summary>
 /// CargoListEntryTN creates an entry into the taskgroup cargo hold list for installations.
 /// </summary>
 /// <param name="Type">Type of installation.</param>
 /// <param name="SizeInTons">tons per installation.</param>
 public CargoListEntryTN(Installation.InstallationType Type, int SizeInTons)
 {
     CargoType = Type;
     Tons = SizeInTons;
 }
        private void copyInWebProjectFiles( Installation installation, WebProject webProject )
        {
            var webProjectFilesFolderPath = EwlStatics.CombinePaths( ConfigurationStatics.InstallationPath, AppStatics.WebProjectFilesFolderName );
            var webProjectPath = EwlStatics.CombinePaths( installation.GeneralLogic.Path, webProject.name );

            // Copy Ewf folder and customize namespaces in .aspx, .ascx, .master, and .cs files.
            var webProjectEwfFolderPath = EwlStatics.CombinePaths( webProjectPath, StaticFileHandler.EwfFolderName );
            IoMethods.DeleteFolder( webProjectEwfFolderPath );
            IoMethods.CopyFolder( EwlStatics.CombinePaths( webProjectFilesFolderPath, StaticFileHandler.EwfFolderName ), webProjectEwfFolderPath, false );
            IoMethods.RecursivelyRemoveReadOnlyAttributeFromItem( webProjectEwfFolderPath );
            var matchingFiles = new List<string>();
            matchingFiles.AddRange( Directory.GetFiles( webProjectEwfFolderPath, "*.aspx", SearchOption.AllDirectories ) );
            matchingFiles.AddRange( Directory.GetFiles( webProjectEwfFolderPath, "*.ascx", SearchOption.AllDirectories ) );
            matchingFiles.AddRange( Directory.GetFiles( webProjectEwfFolderPath, "*.master", SearchOption.AllDirectories ) );
            matchingFiles.AddRange( Directory.GetFiles( webProjectEwfFolderPath, "*.cs", SearchOption.AllDirectories ) );
            foreach( var filePath in matchingFiles )
                File.WriteAllText( filePath, customizeNamespace( File.ReadAllText( filePath ), webProject ) );

            IoMethods.CopyFile(
                EwlStatics.CombinePaths( webProjectFilesFolderPath, AppStatics.StandardLibraryFilesFileName ),
                EwlStatics.CombinePaths( webProjectPath, AppStatics.StandardLibraryFilesFileName ) );
            IoMethods.RecursivelyRemoveReadOnlyAttributeFromItem( EwlStatics.CombinePaths( webProjectPath, AppStatics.StandardLibraryFilesFileName ) );
        }
        void Operation.Execute( Installation genericInstallation, OperationResult operationResult )
        {
            IsuStatics.ConfigureIis( true );
            Console.WriteLine( "Configured IIS Express." );

            // This block exists because of https://enduracode.kilnhg.com/Review/K164316.
            try {
                IsuStatics.ConfigureIis( false );
                Console.WriteLine( "Configured full IIS." );
            }
            catch {
                Console.WriteLine( "Did not configure full IIS." );
            }

            var installation = genericInstallation as DevelopmentInstallation;

            DatabaseOps.UpdateDatabaseLogicIfUpdateFileExists(
                installation.DevelopmentInstallationLogic.Database,
                installation.ExistingInstallationLogic.DatabaseUpdateFilePath,
                true );

            try {
                copyInEwlFiles( installation );
            }
            catch( Exception e ) {
                var message = "Failed to copy {0} files into the installation. Please try the operation again.".FormatWith( EwlStatics.EwlName );
                if( e is UnauthorizedAccessException || e is IOException )
                    throw new UserCorrectableException( message, e );
                throw new ApplicationException( message, e );
            }

            // Generate code.
            if( installation.DevelopmentInstallationLogic.SystemIsEwl ) {
                generateCodeForProject(
                    installation,
                    AppStatics.CoreProjectName,
                    writer => {
                        writer.WriteLine( "using System;" );
                        writer.WriteLine( "using System.Globalization;" );
                        writer.WriteLine( "using System.Reflection;" );
                        writer.WriteLine( "using System.Runtime.InteropServices;" );
                        writer.WriteLine();
                        writeAssemblyInfo( writer, installation, "" );
                        writer.WriteLine();
                        writer.WriteLine( "namespace EnterpriseWebLibrary {" );
                        writer.WriteLine( "partial class EwlStatics {" );
                        CodeGenerationStatics.AddSummaryDocComment( writer, "The date/time at which this version of EWL was built." );
                        writer.WriteLine(
                            "public static readonly DateTimeOffset EwlBuildDateTime = {0};".FormatWith( AppStatics.GetLiteralDateTimeExpression( DateTimeOffset.UtcNow ) ) );
                        writer.WriteLine( "}" );
                        writer.WriteLine( "}" );
                    } );
                generateCodeForProject(
                    installation,
                    "Development Utility",
                    writer => {
                        writer.WriteLine( "using System.Reflection;" );
                        writer.WriteLine( "using System.Runtime.InteropServices;" );
                        writeAssemblyInfo( writer, installation, "Development Utility" );
                    } );
            }
            generateLibraryCode( installation );
            foreach( var webProject in installation.DevelopmentInstallationLogic.DevelopmentConfiguration.webProjects ?? new WebProject[ 0 ] )
                generateWebConfigAndCodeForWebProject( installation, webProject );
            foreach( var service in installation.ExistingInstallationLogic.RuntimeConfiguration.WindowsServices )
                generateWindowsServiceCode( installation, service );
            foreach( var project in installation.DevelopmentInstallationLogic.DevelopmentConfiguration.ServerSideConsoleProjectsNonNullable )
                generateServerSideConsoleProjectCode( installation, project );
            if( installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject != null ) {
                generateCodeForProject(
                    installation,
                    installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject.name,
                    writer => {
                        writer.WriteLine( "using System.Reflection;" );
                        writer.WriteLine( "using System.Runtime.InteropServices;" );
                        writeAssemblyInfo( writer, installation, installation.DevelopmentInstallationLogic.DevelopmentConfiguration.clientSideAppProject.name );
                    } );
            }

            generateXmlSchemaLogicForCustomInstallationConfigurationXsd( installation );
            generateXmlSchemaLogicForOtherXsdFiles( installation );

            if( !installation.DevelopmentInstallationLogic.SystemIsEwl && Directory.Exists( EwlStatics.CombinePaths( installation.GeneralLogic.Path, ".hg" ) ) )
                updateMercurialIgnoreFile( installation );
        }
 void Operation.Execute( Installation genericInstallation, OperationResult operationResult )
 {
     var installation = genericInstallation as RecognizedDevelopmentInstallation;
     installation.ExistingInstallationLogic.InstallServices();
     installation.ExistingInstallationLogic.Start();
 }
Ejemplo n.º 52
0
 /// <summary>
 /// Ensure that Conference is properly installed on each run, attempting to make ".NET File Copy Deployment" a reality.
 /// 
 /// This mostly works, but two problems arise from "File Copy Deployment".  First, there's a large delay upon first run while setup executes.
 /// Second, uninstall is never run if the files are just deleted so niggling things like registry entries, performance counters, event logs,
 /// etc. get left around.
 /// 
 /// Because of this, we still deploy the application to the clients using MSIs which call custom actions that run the Installer classes on both
 /// setup and when Add/Remove Programs -> Remove is called.
 /// 
 /// This Dll knows whether to self-install by checking a registry entry that is set upon installation.  If you delete the files without calling
 /// uninstall, be sure to delete HKLM\SOFTWARE\Microsoft Research\ConferenceXP\ConferenceAPIInstalled before reinstalling Rtp in another location.  The clean way to
 /// uninstall without MSIs or Add/Remove Programs is to call "installutil /u Conference.dll" before deleting the file or by having your
 /// app call Installer.Uninstall on the Conference assembly programatically.  See Installation.cs for an example of how to programmatically
 /// install/uninstall an assembly dependency.
 /// </summary>
 public static void CheckInstalled()
 {
     if (!Installation.Installed)
     {
         // Install myself
         IDictionary state = new Hashtable();
         state.Clear();
         Installation inst = new Installation();
         inst.Install(state);
         inst.Commit(state);
     }
 }
        /// <summary>
        /// Copies the tags from the specified set to the Installation object, excluding InstallationId and UserId (conditionally).
        /// </summary>
        /// <param name="installation">The Installation object to copy tags to.</param>
        /// <param name="tags">The set of tags to copy.</param>
        /// <param name="copyUserId">True to copy the UserId tag. False, otherwise.</param>
        internal static void CopyTagsToInstallation(Installation installation, HashSet<string> tags, bool copyUserId)
        {
            if (tags == null)
            {
                installation.Tags = null;
                return;
            }

            if (tags.Count < 1)
            {
                installation.Tags = new List<string>();
            }

            foreach (string tag in tags)
            {
                bool isInstallationTag = tag.StartsWith(InstallationIdTagPrefix, StringComparison.OrdinalIgnoreCase);
                bool isUserIdTag = tag.StartsWith(UserIdTagPrefix, StringComparison.OrdinalIgnoreCase);

                // Do not copy installation ID.
                if (!isInstallationTag)
                {
                    if (isUserIdTag)
                    {
                        // Copy userId only if copyUserId is true.
                        if (copyUserId)
                        {
                            AddTagToInstallation(installation, tag);
                        }
                    }
                    else
                    {
                        // Copy all other tags.
                        AddTagToInstallation(installation, tag);
                    }
                }
            }
        }
Ejemplo n.º 54
0
 /// <summary>
 /// If licenseType is an evaluation license, returns true. An evaluation license limits the ability of
 /// Rhino to save based on either the number of saves or a fixed period of time.
 /// </summary>
 /// <seealso cref="Installation"/>
 /// <param name="licenseType"></param>
 /// <returns>true if licenseType is an evaluation license. false otherwise</returns>
 public static bool IsInstallationEvaluation(Installation licenseType)
 {
   return (licenseType == Installation.Evaluation ||
           licenseType == Installation.EvaluationTimed);
 }
 bool Operation.IsValid( Installation genericInstallation )
 {
     var installation = genericInstallation as DevelopmentInstallation;
     return installation != null && !installation.DevelopmentInstallationLogic.SystemIsEwl;
 }
Ejemplo n.º 56
0
 public static void Install(CubeSet cs, Installation installation)
 {
     foreach (Cube c in cs.toArray()) {
         installation (c);
     }
 }
 bool Operation.IsValid( Installation installation )
 {
     return installation is RecognizedDevelopmentInstallation;
 }